C#禁止重複執行程式,並激活原托盤程式
阿新 • • 發佈:2019-01-28
static class Program
{
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(int hWnd, int cmdShow);
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32")]
static extern int SetForegroundWindow(int hwnd);
private const int SW_NORMAL = 1; //正常彈出窗體
#region 方法1
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Process currentProcess = Process.GetCurrentProcess();
//判斷程式是否已經啟動
Mutex mutex = new Mutex(false, "GTranslate");
bool Running = !mutex.WaitOne(0, false);
if (!Running)
{
Application.Run(new Form1());
}
else
{
// MessageBox.Show("程式已經執行" + process.MainWindowTitle, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
int WINDOW_HANDLER = FindWindow(null, "資料庫備份"); //程式標題或類名二選1
if (WINDOW_HANDLER > 0)
{
//MessageBox.Show(WINDOW_HANDLER.ToString());
ShowWindowAsync(WINDOW_HANDLER, SW_NORMAL);
SetForegroundWindow(WINDOW_HANDLER);
}
Environment.Exit(0);
}
}
#endregion
}
}
{
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(int hWnd, int cmdShow);
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32")]
static extern int SetForegroundWindow(int hwnd);
private const int SW_NORMAL = 1; //正常彈出窗體
#region 方法1
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Process currentProcess = Process.GetCurrentProcess();
//判斷程式是否已經啟動
Mutex mutex = new Mutex(false, "GTranslate");
bool Running = !mutex.WaitOne(0, false);
if (!Running)
{
Application.Run(new Form1());
}
else
{
// MessageBox.Show("程式已經執行" + process.MainWindowTitle, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
int WINDOW_HANDLER = FindWindow(null, "資料庫備份"); //程式標題或類名二選1
if (WINDOW_HANDLER > 0)
{
//MessageBox.Show(WINDOW_HANDLER.ToString());
ShowWindowAsync(WINDOW_HANDLER, SW_NORMAL);
SetForegroundWindow(WINDOW_HANDLER);
}
Environment.Exit(0);
}
}
#endregion
}
}