C#中在窗体间使用消息来处理相关联的事件

在项目中有这样的需求,在主窗体隐藏时或者主进程运行时对其它窗体的控件或者事件进行控制,而且其它窗体是处于活动状态,而主窗体或者主进程是隐藏在后面的。这个时候使用句柄和消息来处理就比较好解决这些问题了,当然了也可以使用其它方法。比如将其它窗体在主窗体中申明并且定义,使之和主窗体一样一直存在于内存中,在各个窗体中申明公共方法,在主进程需要调用时直接调用即可,但是这样耗费了大量的系统资源。现在使用消息来解决这个问题。下面提供一个小程序,在主窗体中通过句柄和消息来控制子窗体中Label上文字变化和颜色,代码如下:


Windowns的API类

usingSystem;
usingSystem.Runtime.InteropServices;

namespaceTestHwnd
{
publicclassWin32API
{
[DllImport("user32.dll ",CharSet = CharSet.Unicode)]
publicstaticexternIntPtrPostMessage(IntPtr hwnd,intwMsg,stringwParam,stringlParam);

}

}


主窗体程序(发送消息):

usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Runtime.InteropServices;

namespaceTestHwnd
{
publicpartialclassMain : Form
{

//定义了一个子窗体的句柄
publicIntPtr hwndfrmTest;


publicMain()
{
InitializeComponent();
}



privatevoidtimer1_Tick(objectsender,EventArgs e)
{

if(hwndfrmTest!=(IntPtr)0)
{
if(DateTime.Now.Second%3==0)
{
Win32API.PostMessage(hwndfrmTest,0x60,"","");
}

if(DateTime.Now.Second%5==0)
{
Win32API.PostMessage(hwndfrmTest,0x61,"","");
}

}

}


voidButton2Click(objectsender,EventArgs e)
{
frmTest frm=newfrmTest();
frm.Show(this);
}
}

子窗体程序(接收消息)

usingSystem;
usingSystem.Drawing;
usingSystem.Windows.Forms;

namespaceTestHwnd
{
/// <summary>
/// Description of frmTest.
/// </summary>
public partial classfrmTest : Form
{
Main main;
public frmTest()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();

//
//TODO: Add constructor code after the InitializeComponent() call.
//
}

void FrmTest_Load( objectsender,EventArgs e)
{

main =this.OwnerasMain;

//初始化该窗体的句柄

main.hwndfrmTest = this.Handle;
}

/// 重写窗体的消息处理函数DefWndProc,从中加入自己定义消息 MYMESSAGE 的检测的处理入口
protected override void DefWndProc( refMessage m)
{
switch(m.Msg)
{
case 0x60:
{
label1.ForeColor=Color.Red;
label1.Text = DateTime.Now. ToString()+ "-"+ "测试成功。。。。,呵呵,变红了";
}
break;
case 0x61:
{
label1.ForeColor=Color.Blue;
label1.Text = DateTime.Now. ToString()+ "-"+ "测试成功。。。。,呵呵,变蓝了";
}
break;
default:
base. DefWndProc( refm);
break;
}
}



void Button1Click( objectsender,EventArgs e)
{
main.hwndfrmTest =(IntPtr)( 0);
this. Close();
}
}
}













}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值