一、封装一个类发消息
public struct My_lParam
{
public int i;
public string s;
}
public class Note
{
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(
IntPtr hWnd, // 信息发往的窗口的句柄
int Msg, // 消息ID
int wParam, // 参数1
ref My_lParam lParam
);
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
public const int USER = 0x500;
public const int MYMESSAGE = USER + 1;
//向窗体发送消息的函数
public void SendMsgToMainForm(string strUrlMsg)
{
IntPtr ptr = FindWindow(null, "FormMain");
My_lParam m = new My_lParam();
m.s = strUrlMsg;
SendMessage(ptr, MYMESSAGE, 1, ref m);
}
} 二、窗体B调用发消息
Note note = new Note();
note.SendMsgToMainForm(strUrlPath);
三、主窗体处理接收消息
protected override void DefWndProc(ref Message m)
{
switch (m.Msg)
{
//接收自定义消息MYMESSAGE,并显示其参数
case Note.MYMESSAGE:
My_lParam ml = new My_lParam();
Type t = ml.GetType();
ml = (My_lParam)m.GetLParam(t);
string strTest =ml.s
break;
default:
base.DefWndProc(ref m);
break;
}
}
本文介绍了一种使用C#实现窗体间消息传递的方法。通过定义自定义消息类型和利用User32.dll中的SendMessage及FindWindow函数,可以在不同窗体间发送和接收消息。此外,还展示了如何在主窗体中处理接收到的消息。

470

被折叠的 条评论
为什么被折叠?



