Winform学习(四)--消息在不同页面间传递
学习链接:https://blog.csdn.net/winterye12/article/details/77370453
1、新建Msg类
class Msg
{
[DllImport("user32.dll")]
//发送消息
public static extern void PostMessage(IntPtr hWnd, int msg, int wParam, int lParam);
/// <summary>
/// 存放窗口的句柄
/// </summary>
private static List<IntPtr> m_hWndList = new List<IntPtr>();
/// <summary>
/// 加载窗口的句柄
/// </summary>
/// <param name="hWnd"></param>
public static void AddHandle(IntPtr hWnd)
{
if (null != hWnd)
{
m_hWndList.Add(hWnd);
}
}
/// <summary>
/// 移除窗口的句柄
/// </summary>
/// <param name="hWnd"></param>
public static void RemoveHandle(IntPtr hWnd)
{
m_hWndList.Remove(hWnd);
}
public static void PostMsg(int msg, int wParam, int lParam)
{
for (int i = 0; i < m_hWndList.Count; i++)
{
if (null != m_hWndList[i])
{
PostMessage(m_hWndList[i], msg, wParam, lParam);
}
}
}
}
2、页面类中添加
public newPageTest()
{
InitializeComponent();
Msg.AddHandle(this.Handle);//句柄加入消息列表
}
private void cancelBtn_ButtonClick(object sender, EventArgs e)
{
Msg.PostMsg(12000, 0, 0);//发送消息
}
3、待接收消息页面
public Form1()
{
InitializeComponent();
Msg.AddHandle(this.Handle);
}
/// <summary>
/// 重写接收窗体消息的方法
/// </summary>
/// <param name="m"></param>
protected override void DefWndProc(ref Message m)
{
if (m.Msg == 12000)
{
if (m.WParam.ToInt32() == 0)
{
//动作
}
}
}
浙公网安备 33010602011771号