开源 C# 快速开发(十五)进程--Windows 消息
Windows 消息机制是 Windows 操作系统的核心通信方式之一,广泛应用于进程间通信(IPC)和用户界面交互。在 C# 中,通过 P/Invoke 和 Win32 API 可以实现对 Windows 消息的发送、接收和处理。
Windows 消息基础
Windows 消息是一个数据结构,包含消息标识符(如 WM_CLOSE)、附加参数(wParam 和 lParam)以及目标窗口句柄。消息通过系统消息队列或应用程序消息队列传递。
消息处理的核心函数包括 SendMessage(同步发送)和 PostMessage(异步发送)。C# 中通过 [DllImport("user32.dll")] 导入这些 API:
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
消息发送示例
以下代码演示如何向指定窗口发送关闭消息(WM_CLOSE):
const uint WM_CLOSE = 0x0010;
// 获取目标窗口句柄(例如记事本)
IntPtr hWnd = FindWindow("Notepad", null);
if (hWnd != IntPtr.Zero)
{
SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
消息接收与处理
在 C# 中,可以通过重写 WndProc 方法接收消息。例如,在 Windows Forms 中:
protected override void WndProc(ref Message m)
{
const uint WM_HOTKEY = 0x0312;
if (m.Msg == WM_HOTKEY)
{
// 处理热键消息
Console.WriteLine("Hotkey pressed");
}
base.WndProc(ref m);
}
自定义消息
定义和发送自定义消息需注册消息标识符:
const uint WM_USER = 0x0400;
const uint MY_CUSTOM_MESSAGE = WM_USER + 1;
// 发送自定义消息
PostMessage(hWnd, MY_CUSTOM_MESSAGE, IntPtr.Zero, IntPtr.Zero);
// 接收处理
protected override void WndProc(ref Message m)
{
if (m.Msg == MY_CUSTOM_MESSAGE)
{
Console.WriteLine("Custom message received");
}
base.WndProc(ref m);
}
跨进程通信
通过 PostMessage 或 SendMessage 可实现跨进程通信。需确保目标窗口句柄有效,并使用 RegisterWindowMessage 注册全局唯一消息:
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint RegisterWindowMessage(string lpString);
uint messageId = RegisterWindowMessage("MyApp_GlobalMessage");
PostMessage(hWnd, messageId, IntPtr.Zero, IntPtr.Zero);
注意事项
- 权限问题:发送消息到其他进程需足够的权限。
- 同步与异步:
SendMessage会阻塞调用线程,PostMessage不会。 - 64 位兼容性:
wParam和lParam在 32/64 位系统中长度不同,需使用IntPtr。
通过合理利用 Windows 消息机制,可以实现高效的进程间通信和系统交互。结合 C# 的托管代码优势,开发者可以快速构建功能丰富的应用程序。
1018

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



