c++ 串口钩子demo
时间: 2023-08-04 19:35:28 浏览: 83
以下是一个简单的 C++ 串口钩子 demo:
```cpp
#include <Windows.h>
#include <iostream>
HHOOK g_hHook = NULL;
HANDLE g_hCom = INVALID_HANDLE_VALUE;
// 串口消息处理函数
LRESULT CALLBACK COMProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HC_ACTION)
{
// 获取串口句柄
if (g_hCom == INVALID_HANDLE_VALUE)
{
g_hCom = CreateFile(L"COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (g_hCom == INVALID_HANDLE_VALUE)
{
std::cout << "CreateFile failed!" << std::endl;
return 0;
}
}
// 处理串口消息
if (wParam == EV_RXCHAR)
{
char buf[1024] = { 0 };
DWORD dwRead = 0;
if (ReadFile(g_hCom, buf, sizeof(buf), &dwRead, NULL))
{
std::cout << "Received data: " << buf << std::endl;
}
}
}
return CallNextHookEx(g_hHook, nCode, wParam, lParam);
}
int main()
{
// 设置串口钩子
g_hHook = SetWindowsHookEx(WH_GETMESSAGE, COMProc, NULL, GetCurrentThreadId());
if (g_hHook == NULL)
{
std::cout << "SetWindowsHookEx failed!" << std::endl;
return -1;
}
// 消息循环
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// 取消钩子
UnhookWindowsHookEx(g_hHook);
// 关闭串口
if (g_hCom != INVALID_HANDLE_VALUE)
{
CloseHandle(g_hCom);
g_hCom = INVALID_HANDLE_VALUE;
}
return 0;
}
```
这个 demo 中,我们使用了 WH_GETMESSAGE 钩子,来监听所有的消息,并在 COMProc 函数中处理串口消息。在处理串口消息时,我们首先获取了 COM1 串口的句柄,并通过 ReadFile 函数读取串口数据。最后,在程序退出时,我们需要取消钩子并关闭串口。
阅读全文