发送消息
需要的引用:using System.Runtime.InteropServices;
//通过窗口的标题来查找窗口的句柄
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
//消息发送API
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(
IntPtr hWnd, // 信息发往的窗口的句柄
int Msg, // 消息ID
int wParam, // 参数1
int lParam //参数2
);
//自定义窗口名称,例:
public enum WindowsName { 驻留程序, 调试程序,数据同步程序}
//自定义要发送的消息,例:
public enum MsgType { 重大更新系统消息,普通更新系统消息 }
//发送消息的接口
public static void SendMsg(WindowsName winname, MsgType msgtype)
{
IntPtr hwnd = FindWindow(null, winname.ToString());
if(hwnd != IntPtr.Zero)
{
SendMessage(hwnd, 0x61, 5,(int)msgtype);
}
}
接收消息
///重写窗体的消息处理函数DefWndProc,从中加入自己定义消息的检测的处理入口
protected override void DefWndProc(ref Message m)
{
switch (m.Msg)
{
//接收自定义消息MYMESSAGE,并显示其参数
case 0x61:
{
switch ((Win32APIMessage.MsgType)int.Parse(m.LParam.ToString()))
{
case Win32APIMessage.MsgType.收到调试程序重大更新系统消息:
//做操作处理
break;
}
}
break;
default:
base.DefWndProc(ref m);
break;
}
}
委托和事件
所谓的委托其实就是观察者,它会关心某种事件,一旦这种事件被触发,这个观察者就会行动。
举例如下,首先实例化一个观察者类dDownloadProgress,将事件跟我们定义的观察者进行连接,这样,每当onDownLoadProgress事件被触发,就会去通知这个观察者,注意我们连接的时候使用的并不是直接的观察者类实例中的downloader_onDownLoadProgress()方法,而是一个委托,并在这个委托中传递downloader_onDownLoadProgress()方法。即我有一个方法,但我委托你来帮我关联到事件,因为事件只会直接跟委托打交道,而不是具体的某个方法。
public void StartDownload()
{
Downloader downloader = new Downloader();
downloader.onDownLoadProgress += new Downloader.dDownloadProgress(downloader_onDownLoadProgress);
downloader.Start();
isExit = false;
}
public class Downloader
{
//委托
public delegate void dDownloadProgress(long total, long current);
//事件
public event dDownloadProgress onDownLoadProgress;
//开始模拟工作
public void Start()
{
for (int i = 0; i < 100; i++)
{
bool isExit = Setup.isExit;
if (!isExit)
{
if (onDownLoadProgress != null)
onDownLoadProgress(100, i);
System.Threading.Thread.Sleep(100);
}
else
{
return;
}
}
}
}
void downloader_onDownLoadProgress(long total, long current)
{
Control.CheckForIllegalCrossThreadCalls = false;
if (this.InvokeRequired)
{
this.Invoke(new Downloader.dDownloadProgress(downloader_onDownLoadProgress), new object[] { total, current });
long test = current + 1;
label6.Text = test.ToString() + "%";
label6.Show();
}
else
{
this.progressBar1.Maximum = (int)total;
this.progressBar1.Value = (int)current + 1;
}
}