How to make a “popup” (hint, drop-down, popup) window in Winforms?

后端 未结 3 943

How can i make, what i will call, a \"popup\" window\" in WinForms?


Since i used my own made-up word \"popup\", let me give examples of this so-called \"p

3条回答
  •  忘掉有多难
    2021-02-06 12:15

    You want an owned window. In your main form:

    private void showPopup_Click(object sender, EventArgs e)
    {
        PopupForm popupForm = new PopupForm();
        // Make "this" the owner of form2
        popupForm.Show(this);
    }
    

    PopupForm should look like this:

    public partial class PopupForm : Form
    {
        private bool _activating = false;
    
        public PopupForm()
        {
            InitializeComponent();
        }
    
        // Ensure the popup isn't activated when it is first shown
        protected override bool ShowWithoutActivation
        {
            get
            {
                return true;
            }
        }
    
        private const int WM_NCACTIVATE = 0x86;
    
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
    
        protected override void WndProc(ref Message m)
        {
            // The popup needs to be activated for the user to interact with it,
            // but we want to keep the owner window's appearance the same.
            if ((m.Msg == WM_NCACTIVATE) && !_activating && (m.WParam != IntPtr.Zero))
            {
                // The popup is being activated, ensure parent keeps activated appearance
                _activating = true;
                SendMessage(this.Owner.Handle, WM_NCACTIVATE, (IntPtr) 1, IntPtr.Zero);
                _activating = false;
                // Call base.WndProc here if you want the appearance of the popup to change
            }
            else
            {
                base.WndProc(ref m);
            }
        }
    }
    

    And make sure that PopupForm.ShowInTaskbar = false.

提交回复
热议问题