How do I create an “unfocusable” form in C#?

前端 未结 2 1281
醉梦人生
醉梦人生 2020-12-14 21:29

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.<

2条回答
  •  抹茶落季
    2020-12-14 22:12

    This is the "NoFocusForm" I use:

    public class NoFocusForm : Form
    {
        /// From MSDN 
        /// A top-level window created with this style does not become the 
        /// foreground window when the user clicks it. The system does not 
        /// bring this window to the foreground when the user minimizes or 
        /// closes the foreground window. The window should not be activated 
        /// through programmatic access or via keyboard navigation by accessible 
        /// technology, such as Narrator. To activate the window, use the 
        /// SetActiveWindow or SetForegroundWindow function. The window does not 
        /// appear on the taskbar by default. To force the window to appear on 
        /// the taskbar, use the WS_EX_APPWINDOW style.
        private const int WS_EX_NOACTIVATE = 0x08000000;
    
        public NoFocusForm()
        { 
            // my other initiate stuff
        }
    
        /// 
        /// Prevent form from getting focus
        /// 
        protected override CreateParams CreateParams
        {
            get
            {
                var createParams = base.CreateParams;
    
                createParams.ExStyle |= WS_EX_NOACTIVATE;
                return createParams;
            }
        }
    }
    

提交回复
热议问题