private IntPtr MyHookProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { // Handle the message here return IntPtr.Zero; } private void AddHook(HwndSource hwndSource) { HwndSourceHook hook = new HwndSourceHook(MyHookProc); hwndSource.AddHook(hook); } private void RemoveHook(HwndSource hwndSource) { HwndSourceHook hook = new HwndSourceHook(MyHookProc); hwndSource.RemoveHook(hook); }
private HwndSource hwndSource; private void CreateHwndSource(IntPtr hwnd) { hwndSource = HwndSource.FromHwnd(hwnd); AddHook(hwndSource); } private void DestroyHwndSource() { RemoveHook(hwndSource); hwndSource.Dispose(); }In this example, we create an HwndSource object and add a hook procedure to it. We then remove the hook procedure and dispose of the HwndSource object when we are done with it. Package library: PresentationCore.dll.