我們希望能直接跳出已在執行的程式即可,而非開了二個程式,
此時,我們只要在program.cs裡先做檢查就行了
static void Main() { if (frmMain.AlreadyRunning()) { return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); }其中,AlreadyRunning()是宣告frmMain.cs裡
public static bool AlreadyRunning() { /* const int SW_HIDE = 0; const int SW_SHOWNORMAL = 1; const int SW_SHOWMINIMIZED = 2; const int SW_SHOWMAXIMIZED = 3; const int SW_SHOWNOACTIVATE = 4; const int SW_RESTORE = 9; const int SW_SHOWDEFAULT = 10; */ const int swRestore = 9; var me = Process.GetCurrentProcess(); var arrProcesses = Process.GetProcessesByName(me.ProcessName); if (arrProcesses.Length > 1) { for (var i = 0; i < arrProcesses.Length; i++) { if (arrProcesses[i].Id != me.Id) { // get the window handle IntPtr hWnd = arrProcesses[i].MainWindowHandle; // if iconic, we need to restore the window //if (IsIconic(hWnd)) { MessageBox.Show("Already running", "", MessageBoxButtons.OK); ShowWindowAsync(hWnd, swRestore); } // bring it to the foreground SetForegroundWindow(hWnd); break; } } return true; } return false; }
沒有留言:
張貼留言