public void Run(Window owner) { NativeMethods.CBTProc CenterChildHookProc = new NativeMethods.CBTProc(CenterChildCallBack); // 分配新的GCHandle,保护对象不被垃圾回收 _gch = GCHandle.Alloc(CenterChildHookProc); _parent = new WindowInteropHelper(owner).Handle; // 父窗体句柄 // 注意:dwThreadId为System.Threading.Thread.CurrentThread.ManagedThreadId不起作用 _hhk = NativeMethods.SetWindowsHookEx(WH_CBT, CenterChildHookProc, IntPtr.Zero, NativeMethods.GetCurrentThreadId()); }
public MainWindow() { InitializeComponent(); this.WindowState = WindowState.Maximized; // create an instance of the delegate that // won't be garbage collected to avoid: // Managed Debugging Assistant 'CallbackOnCollectedDelegate' :** // 'A callback was made on a garbage collected delegate of type // 'WpfApp1!WpfApp1.MainWindow+NativeMethods+CBTProc::Invoke'. // This may cause application crashes, corruption and data loss. // When passing delegates to unmanaged code, they must be // kept alive by the managed application until it is guaranteed // that they will never be called.' _callback = this.CallBack; _hook = NativeMethods.SetWindowsHookEx( NativeMethods.HookType.WH_MOUSE, _callback, instancePtr: IntPtr.Zero, threadID: NativeMethods.GetCurrentThreadId()); this.Closed += MainWindow_Closed; this.Loaded += MainWindow_Loaded; }