Skip to content
</> Mücahit TopalA developer's notebook

Blog/C#

Creating a Popup Form in C#

Mücahit Topal 1 min read 8,174 views TREN

void ShowPopup(string text, int width, int height)
{
    // Create a form named Popup
    Form Popup = new Form {
        Width = width, // assign the width parameter
        Height = height, // assign the height parameter
        ShowInTaskbar = false, // do not show in the taskbar
        FormBorderStyle = FormBorderStyle.None, // No form borders
        BackColor = Color.CornflowerBlue, // Background color "Cornflower blue"
        StartPosition = FormStartPosition.CenterScreen, // Center the form on the screen
        TopMost = true, // Always on top
        Cursor = Cursors.Hand // Make the cursor a hand
    };
 
    // Form click event
    Popup.Click += delegate{
        this.Dispose(); // close the form when clicked
    };
 
    // Drawing inside the form
    Popup.Paint += delegate {
        // Draw a rectangle around the form (color black = Pens.Black)
        Popup.CreateGraphics().DrawRectangle(Pens.Black, 0, 0, (width - 1), (height - 1));
    };
 
    // Create a label named lbl_text
    Label lbl_text = new Label{
        Left = 30, // 30 pixels from the left
        Top = 30, // 30 pixels from the top
        AutoSize = true, // size the label to fit the text
        Font = new Font(this.Font, FontStyle.Bold), // make the font bold
        Text = text // assign the text parameter
    };
 
    // add the created label to the form
    Popup.Controls.Add(lbl_text);
 
    // show the pop-up form
    Popup.ShowDialog();
}

​

And here is how to use it:

//ShowPopup(notification text, width, height);
ShowPopup("You have 3 new messages!", 185, 80);

 

,,

Share X Facebook LinkedIn WhatsApp

More from this category

Comments 0

No comments yet.

Leave a comment

Comments appear after approval.