主要是應對這種需求:軟件只允許啟動一次。
將這個問題轉化一下,可以這樣描述:對于一個軟件,在啟動一個進程之后,不允許啟動其它進程,如果第二次打開程序,就把已經啟動的那個進程的窗口放到最前端顯示。
C# winfrom應用在啟動之后會首先執行program.cs里的代碼,所以需要在這里下手。啟動后,檢測是否有相同進程名的進程,如果有,就把那個進程的窗口提到前端,然后關閉自己。
用法:把你的program.cs改造成這個樣子:
 static class Program  {    //windows api,用于顯示代碼    [DllImport("user32.dll")]    [return: MarshalAs(UnmanagedType.Bool)]    static extern bool SetForegroundWindow(IntPtr hWnd);    /// <summary>    /// The main entry point for the application.    /// </summary>    [STAThread]    static void Main()    {      //核心代碼      Process currProc = Process.GetCurrentProcess();       Process[] runningProc = Process.GetProcesses();      //檢查規則,看進程名是否相同。可以自己靈活定制,比如需要檢查用戶名之類的。      var searchedProc=from a in runningProc               where a.ProcessName == currProc.ProcessName               select a;       if (searchedProc.Count() > 1)      {        //選出和當前進程進程名相同,但是id不同的那個進程        Process firstProc = searchedProc.FirstOrDefault(a => a.Id != currProc.Id);        IntPtr firstProcWindow = firstProc.MainWindowHandle;        SetForegroundWindow(firstProcWindow);        currProc.Kill();      }      //-------end---------      Application.EnableVisualStyles();      Application.SetCompatibleTextRenderingDefault(false);      Application.Run(new Form1());    }  }====================================================
關于窗口前端顯示和置頂,一共涉及到3個windows的API
   //顯示窗口
   ShowWindow(hWnd, SW_NORMAL);
   //前端顯示
   SetForegroundWindow(hWnd);
   //窗口置頂
   SetWindowPos(hWnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
其中這個SetWindowPos最常用,用于設定窗口的位置,最常見用途是給窗口設定為置頂,等同于winform里的this.TopMost=true;
用法:
WinAPI: SetWindowPos - 改變窗口的位置與狀態
SetWindowPos(
hWnd: HWND; {窗口句柄}
hWndInsertAfter: HWND; {窗口的 Z 順序}
X, Y: Integer; {位置}
cx, cy: Integer; {大小}
uFlags: UINT {選項}
): BOOL;
//hWndInsertAfter 參數可選值:
HWND_TOP = 0; {在前面}
HWND_BOTTOM = 1; {在后面}
HWND_TOPMOST = HWND(-1); {在前面, 位于任何頂部窗口的前面}
HWND_NOTOPMOST = HWND(-2); {在前面, 位于其他頂部窗口的后面}
//uFlags 參數可選值:
SWP_NOSIZE = 1; {忽略 cx、cy, 保持大小}
SWP_NOMOVE = 2; {忽略 X、Y, 不改變位置}
SWP_NOZORDER = 4; {忽略 hWndInsertAfter, 保持 Z 順序}
SWP_NOREDRAW = 8; {不重繪}
SWP_NOACTIVATE = $10; {不激活}
SWP_FRAMECHANGED = $20; {強制發送 WM_NCCALCSIZE 消息, 一般只是在改變大小時才發送此消息}
SWP_SHOWWINDOW = $40; {顯示窗口}
SWP_HIDEWINDOW = $80; {隱藏窗口}
以上就是本文的學習內容,希望大家可以喜歡。
新聞熱點
疑難解答