How do I start a process from C#?

后端 未结 12 2045
北荒
北荒 2020-11-22 03:38

How do I start a process, such as launching a URL when the user clicks a button?

12条回答
  •  梦毁少年i
    2020-11-22 03:54

    Declare this

    [DllImport("user32")]
    private static extern bool SetForegroundWindow(IntPtr hwnd);
    [DllImport("user32")]
    private static extern bool ShowWindowAsync(IntPtr hwnd, int a);
    

    And put this inside your function (note that "checkInstalled" is optional, but if you'll use it, you have to implement it)

    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);
            }
        }
    }
    

    NOTE: I'm not sure if this works when more than one instance of the .exe is running.

提交回复
热议问题