单击menustrip时,禁用“要求”以双击未聚焦的窗口

时间:2010-06-16 21:57:24

标签: c# winforms

对于奇怪的标题感到抱歉,我正在玩WinForms并且我想知道是否有任何方法可以使它不必“双击”窗口来激活一个项目窗户没有聚焦时的menustrip?

目前,如果窗口未聚焦,我首先必须单击窗口以使其聚焦,然后再次单击menustrip项目,即使我的鼠标从一开始就悬停在menustrip项目上方。

提前致谢!

2 个答案:

答案 0 :(得分:9)

尝试将此函数放在Form类中:

protected override void WndProc(ref Message m) {
    int WM_PARENTNOTIFY = 0x0210;
    if (!this.Focused && m.Msg == WM_PARENTNOTIFY) {
        // Make this form auto-grab the focus when menu/controls are clicked
        this.Activate();
    }
    base.WndProc(ref m);
}

答案 1 :(得分:0)

@Detmar的答案中的方法将在窗口被破坏时聚焦窗口(参见https://msdn.microsoft.com/en-us/library/windows/desktop/hh454920(v=vs.85).aspx)。如果您的应用程序中有多个窗口并且您正在退出,那么这可能会导致问题。这是一个在你处理windows时不会触发的东西:

    protected override void WndProc(ref Message m)
    {
        const int WM_PARENTNOTIFY = 0x0210;
        if (!this.Focused && m.Msg == WM_PARENTNOTIFY)
        {
            const int WM_CREATE = 0x0001;
            const int WM_DESTROY = 0x0002;
            const int WM_LBUTTONDOWN = 0x0201;
            const int WM_MBUTTONDOWN = 0x0207;
            const int WM_RBUTTONDOWN = 0x0204;
            const int WM_XBUTTONDOWN = 0x020B;
            const int WM_POINTERDOWN = 0x0246;

            int type = (int)(0xFFFF & (long)m.WParam);
            switch (type)
            {
                case WM_LBUTTONDOWN:
                case WM_MBUTTONDOWN:
                case WM_RBUTTONDOWN:
                case WM_XBUTTONDOWN:
                case WM_POINTERDOWN:
                    // Make this form auto-grab the focus when menu/controls are clicked
                    this.Activate();
                    break;
                case WM_DESTROY:
                case WM_CREATE:
                    //do nothing
                    break;
            }
        }
        base.WndProc(ref m);
    }