在Survey Performance找到的資料.... Copy & Paste 如下
确保程序只有一个实例在运行(C#) - Felix Woo
using System.Threading
using System.Runtime.InteropServices;
public class Form1 : Form
{
[STAThread]
static void Main()
{
bool createdNew;
Mutex m = new Mutex(true, "YourAppName", out createdNew);
if (! createdNew)
{
// app is already running...
MessageBox.Show("Only one instance of this application is allowed at a time.");
return;
}
Application.Run(new Form1());
// keep the mutex reference alive until the normal termination of the program
GC.KeepAlive(m);
}
}
另外 要foreground exising one的話 code below
f your application can run with Full Trust permissions, we can take
this a step further and find the window of the application instnace
already running and bring it to the front for the user:
public class Form1 : Form
{
[STAThread]
static void Main()
{
bool createdNew;
System.Threading.Mutex m = new System.Threading.Mutex(true, "YourAppName", out createdNew);
if (! createdNew)
{
// see if we can find the other app and Bring it to front
IntPtr hWnd = FindWindow("WindowsForms10.Window.8.app3", "YourAppName");
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;
}
Powered by ScribeFire.
沒有留言:
張貼留言