简体   繁体   中英

WPF stop mouse down event gaining Application focus

In WinForms I used the following block of code to stop the application gaining focus by being clicked on:

private const int WM_MOUSEACTIVATE = 0x0021;
private const int MA_NOACTIVATEANDEAT = 0x0004;

protected override void WndProc(ref Message m)
{
   if (m.Msg == WM_MOUSEACTIVATE)
   {
       m.Result = (IntPtr)MA_NOACTIVATEANDEAT;
       return;
   }
   base.WndProc(ref m);
}

Is there any alternative to this in a WPF application? Can I use a HwndSource? Here is what I have so far (WM_MOUSEACTIVATE alone does not work as required and the application still gets focus):

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)
{
   // Handle messages...
   int WM_MOUSEACTIVATE = 0x0021;
   int WM_LBUTTONDOWN = 0x0201; //513
   int WM_LBUTTONUP = 0x0202; //514
   int WM_LBUTTONDBLCLK = 0x0203; //515
    if (msg == WM_MOUSEACTIVATE || msg == MA_NOACTIVATEANDEAT || msg == WM_LBUTTONDOWN || msg == WM_LBUTTONUP || msg == WM_LBUTTONDBLCLK)
   {
      handled = true;
   }
   return IntPtr.Zero;
}

How can I get the Message Result?

Resolved by using:

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
   // Handle messages...
   int WM_MOUSEACTIVATE = 0x0021;
   if (msg == WM_MOUSEACTIVATE )
   {
      handled = true;
      return new IntPtr(MA_NOACTIVATEANDEAT); 
   }
   return IntPtr.Zero;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM