Let us look at a simple C# Windows Forms MessageBox example.
Example 1: HelloWorldMessageBox
This example will comprise the following files:
HelloWorldMessageBox.cs
Step 1: Create Project
- The first step is to create a C# Project.
- Go to
FILE-->New-->Project
to create a new project.
Step 2: Write Code
Write Code as follows:
*(a). HelloWorldMessageBox.cs
Create a file named HelloWorldMessageBox.cs
Here is the full code
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Examples {
class MainClass {
public static void Main() {
Application.EnableVisualStyles();
Button button = new Button();
button.Text = "Click me";
button.Location = new Point(10, 10);
button.Width = 90;
button.Click += delegate(object sender, EventArgs e) {
MessageBox.Show("Hello, World!");
};
Form form = new Form();
form.Text = "Hello World Form";
form.Controls.Add(button);
Application.Run(form);
}
}
}
Run
Simply copy the source code into your C# Project,Build and Run. Alternatively download the code using the links provided below, then open the .csproj
project, build and run.
Reference
Download the code using the below links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
Example 2: MessageBox
This example will comprise the following files:
MessageBox.cs
Step 1: Create Project
- The first step is to create a C# Project.
- Go to
FILE-->New-->Project
to create a new project.
Step 2: Write Code
Write Code as follows:
*(a). MessageBox.cs
Create a file named MessageBox.cs
Here is the full code
using System;
using System.Windows.Forms;
namespace Examples {
class Form1 : Form {
// The main entry point for the application.
public static void Main() {
Application.EnableVisualStyles();
Application.Run(new Form1());
}
public Form1() {
buttonShowMessage.Location = new System.Drawing.Point(10, 10);
buttonShowMessage.Width = 100;
buttonShowMessage.Text = "MessageBox";
buttonShowMessage.Click += delegate(object sender, EventArgs e) {
DialogResult result = MessageBox.Show("Hello, World!", "Message", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
labelDialogResult.Text = string.Format("DialogResult = {0}", result);
};
labelDialogResult.Location = new System.Drawing.Point(10, 45);
labelDialogResult.Width = 200;
StartPosition = FormStartPosition.Manual;
Location = new System.Drawing.Point(400, 200);
Text = "MessageBox example";
Controls.AddRange(new Control[] { buttonShowMessage, labelDialogResult});
}
private Button buttonShowMessage = new Button();
private Label labelDialogResult = new Label();
}
}
Run
Simply copy the source code into your C# Project,Build and Run. Alternatively download the code using the links provided below, then open the .csproj
project, build and run.
Reference
Download the code using the below links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |