【Winform】两程序相互调用前置显示

有A&B两个程序,程序A调用程序B, 如果B已运行时将B前置显示 B未打开时开始运行

private void button1_Click(object sender, EventArgs e)
{
    try
    {
		Process[] pps = System.Diagnostics.Process.GetProcessesByName("cmd");
		var helpw = from pc in pps where pc.MainWindowTitle == "XXX" select pc;

		if (helpw.Count() > 0)
		{
			HandleRunningInstance(pps[0]);
		}
		else
		{
			System.Diagnostics.Process.Start($"cmd");
		}
    }
    catch (Exception ex)
    {
		System.Diagnostics.Debug.Assert(false, ex);
    }
}

private static void HandleRunningInstance(Process instance)
{
    /*
    https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-showwindow 
    */
    ShowWindowAsync(instance.MainWindowHandle, 1); //调用api函数,正常显示窗口
    SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端
}

[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(System.IntPtr hWnd);

posted @ 2019-10-27 09:29  叫夏洛啊  阅读(256)  评论(0编辑  收藏  举报