c++ - 监视剪贴板更改
订阅 WM_CLIPBOARDUPDATE消息使用 AddClipboardFormatListener需要消息队列和消息泵。对于控制台应用程序,这可以通过 message-only window 来完成以及相应的消息循环。下面是一些实现这两者的准系统代码。
#include <windows.h>
#include <stdio.h>
LRESULT CALLBACK ClipWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static BOOL bListening = FALSE;
switch(uMsg)
{
case WM_CREATE:
bListening = AddClipboardFormatListener(hWnd);
return bListening ? 0 : -1;
case WM_DESTROY:
if(bListening)
{
RemoveClipboardFormatListener(hWnd);
bListening = FALSE;
}
return 0;
case WM_CLIPBOARDUPDATE:
printf("WM_CLIPBOARDUPDATE\n");
return 0;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
int main()
{
WNDCLASSEX wndClass = { sizeof(WNDCLASSEX) };
wndClass.lpfnWndProc = ClipWndProc;
wndClass.lpszClassName = L"ClipWnd";
if(!RegisterClassEx(&wndClass))
{ printf("RegisterClassEx error 0x%08X\n", GetLastError()); return 1; }
HWND hWnd = CreateWindowEx(0, wndClass.lpszClassName, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
if(!hWnd)
{ printf("CreateWindowEx error 0x%08X\n", GetLastError()); return 2; }
printf("Press ^C to exit\n\n");
MSG msg;
while(BOOL bRet = GetMessage(&msg, 0, 0, 0)) {
if(bRet == -1)
{ printf("GetMessage error 0x%08X\n", GetLastError()); return 3; }
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
https://stackoverflow.com/questions/65840288/monitor-clipboard-changes-c-for-all-applications-windows