如何防止焦点窃取,但仍然能通过Alt+Tab返回我的应用程序并获取焦点?

7

按照微软的指南,我的WPF应用程序的App构造函数包含以下代码以实现正确的焦点行为:

HwndSource.DefaultAcquireHwndFocusInMenuMode = false;
Keyboard.DefaultRestoreFocusMode = RestoreFocusMode.None;

作为这篇文章中所解释的,这些设置可以防止焦点窃取。
然而,将DefaultRestoreFocusMode设置为None会产生负面影响。当使用Alt+Tab离开WPF应用程序并返回时,WPF应用程序不会获得焦点。但是,如果我不将DefaultRestoreFocusMode设置为none,则会按预期获得焦点。有没有办法在防止焦点窃取的同时,通过Alt+Tab返回到WPF应用程序时仍然保持焦点?

我无法复制这种行为,可能是因为我遗漏了重要的细节。我假设Application.Activated事件没有用处? - ianschol
1个回答

3
我可以通过以下方式防止我的wpf窗口获得焦点,并且仍然可以使用ALT-TAB或单击任务栏项来激活它。
您需要更改窗口的样式,以便其无法激活。请参考以下代码:
var yourWindow = new YourWindowType();
//set the windowstyle to noactivate so the window doesn't get focus
yourWindow.SourceInitialized += (s, e) =>
{
  var interopHelper = new WindowInteropHelper(yourWindow);
  int exStyle = User32.GetWindowLong(interopHelper.Handle, (int)WindowLongFlags.GWL_EXSTYLE);
  User32.SetWindowLong(interopHelper.Handle, (int)WindowLongFlags.GWL_EXSTYLE, exStyle | (int)WindowStylesEx.WS_EX_NOACTIVATE);

  //If you have trouble typing into your form's textboxes then do this
  ElementHost.EnableModelessKeyboardInterop(yourWindow);
};

这是我额外添加的一项预防措施,同时它还可以让您在没有边框的情况下拖动窗口:
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
  switch (msg)
  {
    //don't activate the window when you click on it.
    case WindowMessage.WM_MOUSEACTIVATE:  
      handled = true;
      return (IntPtr)MouseActivate.MA_NOACTIVATE;
    //For Borderless Windows: occurs while dragging. it reports new position before it has been finalized.
    //otherwise you wont see the window moving while you're dragging it 
    case WindowMessage.WM_MOVING: 
      RECT rect = (RECT)Marshal.PtrToStructure(lParam, typeof(RECT));
      User32.SetWindowPos(new WindowInteropHelper(this).Handle, Hwnd.HWND_TOPMOST, 
                          rect.Left, rect.Top, rect.Width, rect.Height, 
                          SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOSIZE);
      break;
  }
  return IntPtr.Zero;
}

这些代码添加了一个钩子,以便在WPF中实际调用WndProc:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
  HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
  if (source == null) return;
  source.AddHook(WndProc);
}

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
  HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
  if (source == null) return;
  source.RemoveHook(WndProc);
}

提醒您一下..即使您没有焦点,此方法仍然有效:

   private void WpfPillForm_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      this.DragMove();
    }

以下是 Win32 API 的声明,这样您就不必查找了:
    [StructLayout(LayoutKind.Sequential)]
    public struct WINDOWPOS
    {
        public IntPtr hwnd;
        public IntPtr hwndInsertAfter;
        public int x;
        public int y;
        public int cx;
        public int cy;
        public int flags;
    }

[StructLayout(LayoutKind.Sequential)]
struct RECT
{
    public int left, top, right, bottom;
}

  public static class MouseActivate
  {
    public const int MA_ACTIVATE = 1;
    public const int MA_ACTIVATEANDEAT = 2;
    public const int MA_NOACTIVATE = 3;
    public const int MA_NOACTIVATEANDEAT = 4;
  }

  public enum WindowLongFlags : int
  {
    GWL_EXSTYLE = -20,
    GWLP_HINSTANCE = -6,
    GWLP_HWNDPARENT = -8,
    GWL_ID = -12,
    GWL_STYLE = -16,
    GWL_USERDATA = -21,
    GWL_WNDPROC = -4,
    DWLP_USER = 0x8,
    DWLP_MSGRESULT = 0x0,
    DWLP_DLGPROC = 0x4
  }

    public const int WM_MOVING = 0x0216;
    public const uint WS_EX_NOACTIVATE = 0x08000000,

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int GetWindowLong(IntPtr hwnd, int index);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接