Sending Windows Message in C#


This is a simple C# source code that shows how to "Send Window message" between 2 forms. What I did is I create a class called delegate.cs, which inherits from System.EventArgs.

In the Header of Form2, add the code bellow:

public class Form2 : System.Windows.Forms.Form
{
public delegate void UserRequest(object sender,System.EventArgs e);
public event UserRequest OnUserRequest;
.....

In the MainFrm :

Form2 Frm=
new Form2(); //need to intialize before use...
private
void
InitializeComponent()
{
Frm.OnUserRequest +=
new Form2.UserRequest(UserReq);
.....
private void UserReq(object sender, System.EventArgs e)
{
UserRequestEventArgs ee = (UserRequestEventArgs) e;
this.textBox1.Text= ee.Request.ToString();
}

In MSVC++, window message can be send using SendMessage(), but in C# message can be sent using event, as mention about. Hope this code will help those who familiar with SendMessage().

Banu Cosmin added: A useful tip to know is that when closing a form, if you want the form not to be closed, but instead just hidden (or some other action to be performed), you just add an event handler for the form's Closing event, where you specify to cancel the action:

e.Cancel = true;


Similar Articles