Make a form not focusable in C#

前端 未结 2 1530
忘了有多久
忘了有多久 2020-12-06 10:51

I\'m wanting to write a virtual keyboard, like windows onscreen keyboard for touchscreen pcs. But I\'m having problem with my virtual keyboard stealing the focus from the ap

相关标签:
2条回答
  • 2020-12-06 11:02

    Its solved!

    I've tried the solution from gehho, but I also needed to override the CreateParams method:

    private const int WS_EX_NOACTIVATE = 0x08000000;
    protected override CreateParams CreateParams
    {
        get
        {
            var createParams = base.CreateParams;
    
            createParams.ExStyle |= WS_EX_NOACTIVATE;
            return createParams;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 11:06

    Instead of trying to reset the active window after your one has been clicked, I would rather try to prevent your window from receiving focus/being activated.

    Have a look at this article. At the end, the author briefly explains how this can be done:

    How can I prevent my window from getting activation and focus when shown?

    In Windows Forms 2.0 there is a new property called ShowWithoutActivation – which you would need to override on the Form. In native applications you can use SetWindowPos with the SWP_NOACTIVATE flag or the ShowWindow with the SW_SHOWNA flag.

    Furthermore, in this article he provides a code example for Windows Forms:

    If you want a full-on form, you can now override a property called ShowWithoutActivation:

    public class NoActivateForm : Form 
    {
        protected override bool ShowWithoutActivation => true;  
    }

    Keep in mind this does not “prevent” activation all the time – you can still activate by calling the Activate(), Focus()… etc methods. If you want to prevent clicks on the client area from activating the window, you can handle the WM_MOUSEACTIVATE message.

    private const int WM_MOUSEACTIVATE = 0x0021, MA_NOACTIVATE = 0x0003;
    
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_MOUSEACTIVATE) 
        {
             m.Result = (IntPtr)MA_NOACTIVATE;
             return;
        }
        base.WndProc(ref m);
    }
    0 讨论(0)
提交回复
热议问题