![](/img/trans.png)
[英]Clicking on Notification Area Network Icon blocks TcpClient from receiving data
[英]Returning to Window previously selected before clicking Notification Area Icon
我構建了一個帶有“通知區域”圖標的應用程序,單擊該圖標將彈出一個專為單擊而設計的表單,然后用戶可以返回到自己之前做的事情。
當前,我正在使用this.Hide()
刪除表單(當表單中發生所需的事件時,或者當表單被Deactivated
),但是當我這樣做時,Windows會將用戶設置為任務欄。 在單擊“通知區域”圖標之前,如何獲得將用戶焦點返回到其所在窗口的信息?
我設法找出方法。 我使用以下代碼:
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int SetForegroundWindow(IntPtr hwnd);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr GetWindow(IntPtr hwnd, int wFlag);
private void switchToLast() {
IntPtr thisWindow = GetForegroundWindow();
IntPtr lastWindow = GetWindow(thisWindow, 3);
SetForegroundWindow(lastWindow);
this.Hide();
}
我發現了很多有關該問題的參考,這就是我到目前為止的內容。 此示例與我發現的其他示例之間的主要區別是GetWindow(thisWindow, 3)
,在其他示例中,第二行是2,我將其更改為3。我相信這是因為將其設置為2可以得到指向任務欄的指針。
與其試圖事后解決這個問題,不如在應用程序首次獲得關注時就應首先確定它。 換句話說,越早發現它越好。
顯而易見的解決方案是處理WM_SETFOCUS
或WM_ACTIVATE
消息,它們將句柄作為lParam
傳遞到先前處於活動狀態的窗口。 不幸的是,這僅適用於同一線程中的Windows。 否則, lParam
將為NULL
。
因此,您需要使用WM_ACTIVATEAPP
,它將擁有被停用的窗口的線程的標識符作為lParam
傳遞。 獲得線程標識符后,使用GetGUIThreadInfo
函數確定該線程中的活動窗口。 無論哪個進程擁有該窗口,此方法都有效,因此不受上面針對WM_SETFOCUS
和WM_ACTIVATE
討論的限制。
跟蹤此窗口句柄,並在完成后簡單地將焦點恢復到該窗口句柄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.