防止多重启动之调用Api (效果:第二次启动程序则前一进程的窗口跳到最前)
using System.Threading;
private const int SW_NORMAL = 1; // see WinUser.h for definitions
private const int SW_RESTORE = 9;
[DllImport("User32",EntryPoint="FindWindow")]
static extern IntPtr FindWindow(string className, string windowName);
[DllImport("User32",EntryPoint="SendMessage")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("User32",EntryPoint="SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32",EntryPoint="SetWindowPlacement")]
private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
[DllImport("User32",EntryPoint="GetWindowPlacement")]
private static extern bool GetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
private struct POINTAPI
{
public int x;
public int y;
}
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
private struct WINDOWPLACEMENT
{
public int length;
public int flags;
public int showCmd;
public POINTAPI ptMinPosition;
public POINTAPI ptMaxPosition;
public RECT rcNormalPosition;
}
//Main
static void Main()
{
bool createdNew;
System.Threading.Mutex m = new System.Threading.Mutex(true, "yourApp", out createdNew);
if (! createdNew)
{
// see if we can find the other app and Bring it to front
IntPtr hWnd = FindWindow(null, "form1deText");
if(hWnd != IntPtr.Zero)
{
form1.WINDOWPLACEMENT placement = new form1.WINDOWPLACEMENT();
placement.length = Marshal.SizeOf(placement);
GetWindowPlacement(hWnd, ref placement);
if(placement.showCmd != SW_NORMAL)
{
placement.showCmd = SW_RESTORE;
SetWindowPlacement(hWnd, ref placement);
SetForegroundWindow(hWnd);
}
}
return;
}
Application.Run(new form1());
// keep the mutex reference alive until the normal termination of the program
GC.KeepAlive(m);
}