我打電話HwndSource.AddHook()是為了讓消息在我的 WPF 窗口中處理。我想知道我是否需要HwndSource.RemoveHook()在窗口被銷毀時調用 - 這個窗口不是 MainWindow。如果是這樣,稱它為 ( Closing()) 的正確位置是什么?當窗口被銷毀時,似乎 Hooks 被刪除了。protected override void OnSourceInitialized(EventArgs e){ base.OnSourceInitialized(e); HwndSource source = PresentationSource.FromVisual(this) as HwndSource; source.AddHook(WndProc);}private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled){ if (NativeMethods.UWM_SHOWMYAPP == msg) { if (this.WindowState == WindowState.Minimized) this.WindowState = WindowState.Normal; this.Activate(); handled = true; } return IntPtr.Zero;}void StatusWindow_Closing(object sender, CancelEventArgs e){ HwndSource source = PresentationSource.FromVisual(this) as HwndSource; source.RemoveHook(WndProc);} 在這里刪除時我又得到了HwndSource。這個可以嗎?還是我應該保留該source對象Add()并將其用于Remove()?
1 回答

藍山帝景
TA貢獻1843條經驗 獲得超7個贊
如果是這樣,調用它 (Closing()) 的正確位置是什么?
您可以覆蓋該OnClosed方法。
這個可以嗎?還是我應該保留用于的源對象Add()并將其用于Remove()?
它“沒問題”,但沒有必要PresentationSource.FromVisual多次調用和轉換結果。這可能是我會怎么做:
private HwndSource _source;
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
_source = PresentationSource.FromVisual(this) as HwndSource;
_source.AddHook(WndProc);
}
protected override void OnClosed(EventArgs e)
{
_source.RemoveHook(WndProc);
base.OnClosed(e);
}
- 1 回答
- 0 關注
- 79 瀏覽
添加回答
舉報
0/150
提交
取消