6

我试图让一个特定的 WPF 窗口保持焦点,这意味着它在失去焦点时不应该改变窗口样式(例如标准的 Windows 任务栏)。为了实现这一点,我连接到WndProc检查WM_NCACTIVATEorWM_ACTIVATE是否设置为 false ( wParam == 0),然后将消息标记为handled = true;阻止 Window 处于非活动状态。这是一些示例代码:

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

private const uint WM_NCACTIVATE = 0x0086;
private const int WM_ACTIVATE = 0x0006;
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    if (msg == WM_NCACTIVATE)
    {
        if (wParam == new IntPtr(0))
            handled = true;
    }
    if (msg == WM_ACTIVATE)
    {

        if (wParam == new IntPtr(0))
            handled = true;
    }
    return IntPtr.Zero;
}

但是,通过这样做,在此主窗口中创建的所有其他 WPF 窗口

var f = new Window();
f.ShowDialog();

永远不会收到焦点,尽管它们是可见的,但窗口不会对客户区域中的用户输入做出反应,而且对于 Windows 最小化、最大化和关闭按钮也是如此。我显然做错了什么,所以关于如何以正确的方式做到这一点的任何建议或指示?

4

1 回答 1

4

即使窗口失去焦点也保持 WPF 窗口的视觉样式处于活动状态的解决方案是这样处理WM_NCACTIVATE

private const uint WM_NCACTIVATE = 0x0086;

private IntPtr WndProc(IntPtr hwnd, int msg, 
         IntPtr wParam, IntPtr lParam, ref bool handled)
{
    var returnvalue = IntPtr.Zero;
    if (msg == WM_NCACTIVATE)
    {
        //replace the wParam (true/false) which indicates 
            //active/inactive with always true
        returnvalue = DefWindowProc(hwnd, WM_NCACTIVATE, 
                     new IntPtr(1), new IntPtr(-1));
        handled = true;
    }
}


[DllImport("user32.dll")]
static extern IntPtr DefWindowProc(IntPtr hWnd, WindowsMessages uMsg, IntPtr wParam, IntPtr lParam);
于 2013-06-27T14:34:08.450 回答