Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

.net - How do I create an "unfocusable" form in C#?

I'm looking to create a form in C# that cannot accept focus, i.e. when I click a button on the form, focus is not stolen from the application that currently has the focus.

See the Windows on-screen keyboard for an example of this. Note that when you click a button, the focus is not taken from the application you're currently using.

How can I implement this behaviour?

Update:

Turns out it's as simple as overriding the CreateParams property and adding WS_EX_NOACTIVATE to the extended window style. Thanks for pointing me in the right direction!

Unfortunately this has the undesirable side-effect that it messes with form movement, i.e. you can still drag and drop the form around the screen but the window's border is not displayed while dragging so it's difficult to precisely position it.

If anyone knows how to solve this it would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To disable activation by mouse:

class NonFocusableForm : Form
{
    protected override void DefWndProc(ref Message m)
    {
        const int WM_MOUSEACTIVATE = 0x21;
        const int MA_NOACTIVATE = 0x0003;

        switch(m.Msg)
        {
            case WM_MOUSEACTIVATE:
                m.Result = (IntPtr)MA_NOACTIVATE;
                return;
        }
        base.DefWndProc(ref m);
    }
}

To show form without activation (the only one way that worked for me in case of borderless form):

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr handle, int flags);

    NativeMethods.ShowWindow(form.Handle, 8);

Standard way to do this (seems like it doesn't work for all form styles):

    protected override bool ShowWithoutActivation
    {
        get { return true; }
    }

If there are other ways of activating the form, they can be suppressed in similar manner.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...