Windows form modal dialog

Time:2021-1-26

Modal dialog refers to the window where users can only interact with the current dialog, such as message dialog and user waiting window. Of course, this is not a fixed use. Windows form has provided the method of ShowDialog () to realize modal dialog. But the interface effect is a little single, so this article only adds some interface effect optimization for modal dialog box.

On the Internet, many people use repaint onpaint method to achieve the effect of mask layer, but here we can use a relatively simple method to achieve it, that is, multiple windows overlap, first realize a mask layer window to cover the system window, and then pop up the dialog window. The specific code is as follows

//---------------- DialogForm.cs Implementation in window class
public void ShowDialog(string message)
{
    using (Form overlay = new Form())
    {
        //Mask layer window settings
        overlay.FormBorderStyle = FormBorderStyle.None;
        overlay.StartPosition = FormStartPosition.Manual;
        overlay.BackColor  =  Color.Black ; // window background color
        overlay.Opacity  =7; // background transparency
        overlay.WindowState  =  FormWindowState.Maximized ; // maximize the window
        overlay.TopMost  =True; // window top
        overlay.ShowInTaskbar  =False; // hide the window in the taskbar
        overlay.Show();
        this.label2.Text = message;
        this.Owner = overlay; 
        this.TopMost = true;
        this.ShowDialog();
    }
}

Call in //----------------Form1.cs
 New dialogform(). ShowDialog ("this is a message prompt box");