上一篇介绍了一下怎么避免程序的重复启动
对于如何将已经启动的窗口再一次显示到最前面没有涉及到。
现在来说一下。
首先 添加一下命名空间:
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
添加以下常量和引用:
public const int SW_HIDE = 0;//隐藏
public const int SW_NORMAL = 1;//普通
public const int SW_SHOWMINIMIZED = 2;//最小化
public const int SW_SHOWMAXIMIZED = 3;//最大化
[DllImport("User32.dll")]
public static extern void SetForegroundWindow(IntPtr hwnd);
[DllImport("User32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("User32.dll")]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, IntPtr pProcId);
[DllImport("User32.dll")]
public static extern bool AttachThreadInput(int idAttach, int idAttachTo, int fAttach);
[DllImport("User32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
在Main函数里添加一下代码(加粗字体部分)
蓝色字体为程序名,也就是进程名
static void Main(string[] args)
{
Process[] plist = Process.GetProcesses();
int cid = Process.GetCurrentProcess().Id;
for (int i = 0; i < plist.Length; i++)
{
if (cid != plist[i].Id)
{
string s = plist[i].ProcessName;
if (s == @"MstProducts")
{
ShowWindowAsync(plist[i].MainWindowHandle, SW_NORMAL);
SetForegroundWindow(plist[i].MainWindowHandle);
return;
}
}
}
Application.Run(new frmProdMenu());
}