当用户点击按钮时,我应该如何启动进程,例如打开一个URL?
正如Matt Hamilton所建议的那样,如果你对进程控制有限,则可以使用System.Diagnostics.Process类的静态Start方法进行快速处理...
using System.Diagnostics;
...
Process.Start("process.exe");
另一种选择是使用 Process 类的实例。这样做可以更好地控制进程,包括调度、运行窗口类型,以及最有用的是等待进程完成的能力。
using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.
这种方法比我提到的更加具有控制性。
正如Matt所说,使用Process.Start。
您可以传递一个URL或文档,它们将由注册的应用程序启动。
示例:
Process.Start("Test.Txt");
这将启动Notepad.exe并加载Text.Txt。
Win32Exception
(0x80004005) "没有与此操作关联的指定文件的应用程序" - Yousha Aleayoub我在自己的程序中使用了以下内容。
Process.Start("http://www.google.com/etc/etc/test.txt")
虽然很基础,但对我来说已经足够了。
class ProcessStart
{
static void Main(string[] args)
{
Process notePad = new Process();
notePad.StartInfo.FileName = "notepad.exe";
notePad.StartInfo.Arguments = "ProcessStart.cs";
notePad.Start();
}
}
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "/YourSubDirectory/yourprogram.exe");
Process.Start(new ProcessStartInfo(path));
System.Diagnostics.Process.Start("Example.exe");
同样的方式可以用于处理URL。只需要将你的URL放在这个()
之间即可。
示例:
System.Diagnostics.Process.Start("http://www.google.com");
如果在Windows系统上使用:
Process process = new Process();
process.StartInfo.FileName = "Test.txt";
process.Start();
适用于 .Net Framework,但对于 Net core 3.1,还需要将 UseShellExecute 设置为 true。
Process process = new Process();
process.StartInfo.FileName = "Test.txt";
process.StartInfo.UseShellExecute = true;
process.Start();
声明这个
[DllImport("user32")]
private static extern bool SetForegroundWindow(IntPtr hwnd);
[DllImport("user32")]
private static extern bool ShowWindowAsync(IntPtr hwnd, int a);
if (ckeckInstalled("example"))
{
int count = Process.GetProcessesByName("example").Count();
if (count < 1)
Process.Start("example.exe");
else
{
var proc = Process.GetProcessesByName("example").FirstOrDefault();
if (proc != null && proc.MainWindowHandle != IntPtr.Zero)
{
SetForegroundWindow(proc.MainWindowHandle);
ShowWindowAsync(proc.MainWindowHandle, 3);
}
}
}
注意:我不确定在运行多个 .exe 实例时是否有效。