|
上次发的鼠标连点器实现源码,利用Sleep函数延时。根据 TinaZerotwo 的说法,Sleep()函数来等待按键事件,这会导致线程被阻塞,无法响应其他事件。更好的方式是使用消息循环或事件驱动的机制来监听键盘事件。于是我修改了一下,利用系统自带的timer实现定时触发。因为timer需要有界面支持,所以自己做了一个简单的界面。
源码和可执行文件都放在打包文件里,可以自行编译,也可以自行修改以实现自己的目的。
源码也贴在这里:
- #include <windows.h>
- #include <iostream>
- #include <stdio.h>
- using namespace std;
- #define IDT_TIMER1 1
- LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM ) ;
- int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow )
- {
- static TCHAR szAppName[] = TEXT( "demo" ) ;
- HWND hwnd ;
- MSG msg ;
- WNDCLASS wndclass ;
- wndclass.lpfnWndProc = WndProc ;
- wndclass.style = CS_HREDRAW | CS_VREDRAW ;
- wndclass.hInstance = hInstance ;
- wndclass.cbClsExtra = 0 ;
- wndclass.cbWndExtra = 0 ;
- wndclass.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH) ;
- wndclass.hCursor = LoadCursor( NULL, IDC_ARROW ) ;
- wndclass.hIcon = LoadIcon( NULL, IDI_APPLICATION ) ;
- wndclass.lpszClassName = szAppName ;
- wndclass.lpszMenuName = NULL ;
-
- if( !RegisterClass(&wndclass) )
- {
- MessageBox( NULL, TEXT("无法注册窗口类!"), TEXT("错误"), MB_OK | MB_ICONERROR ) ;
- return 0 ;
- }
- hwnd = CreateWindow( szAppName, TEXT("test"), WS_OVERLAPPEDWINDOW,
- CW_USEDEFAULT, CW_USEDEFAULT,
- CW_USEDEFAULT, CW_USEDEFAULT,
- NULL, NULL, hInstance, NULL ) ;
- ShowWindow( hwnd, iCmdShow ) ;
- UpdateWindow( hwnd ) ;
- while( GetMessage(&msg, NULL, 0, 0) )
- {
- TranslateMessage( &msg ) ;
- DispatchMessage( &msg ) ;
- }
- return msg.wParam ;
- }
- LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam )
- {
- static HWND btn,btn2;
- static POINT p;
- static HWND hdc;
- switch( message )
- {
- case WM_CREATE:
- btn = CreateWindow( TEXT("button"), TEXT("开始点击"),
- WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON,
- 20, 20, 120, 20,
- hwnd, (HMENU)3, ((LPCREATESTRUCT) lParam) -> hInstance, NULL ) ;
- return 0 ;
- case WM_COMMAND:
- switch(LOWORD(wParam))
- {
- case 3:
- switch(HIWORD(wParam))
- {
- case BN_CLICKED:
- MessageBox( NULL, TEXT("将鼠标置于需要连续点击的位置,按下UP键开始鼠标连续点击。DOWN键结束本次点击。"), TEXT("提示信息!"), MB_OK | MB_ICONERROR ) ;
- while(!(GetAsyncKeyState(VK_UP) & 0x8000)){
- Sleep(20);
- }
- GetCursorPos(&p);
- hdc = WindowFromPoint(p);
- ScreenToClient(hdc, &p);
- SetTimer(hwnd,IDT_TIMER1,10,(TIMERPROC)NULL);
- break ;
- }
- break ;
- }
- return 0 ;
- case WM_TIMER:
- switch (wParam)
- {
- case IDT_TIMER1:
- SendMessage(hdc,WM_LBUTTONDOWN,MK_LBUTTON,MAKELONG(p.x,p.y));
- SendMessage(hdc,WM_LBUTTONUP,MK_LBUTTON,MAKELONG(p.x,p.y));
- if(GetAsyncKeyState(VK_DOWN) & 0x8000){
- KillTimer(hwnd,IDT_TIMER1);
- }
- break;
- }
- return 0 ;
- case WM_DESTROY:
- KillTimer(hwnd,IDT_TIMER1);
- PostQuitMessage(0) ;
- return 0 ;
- }
- return DefWindowProc( hwnd, message, wParam, lParam ) ;
- }
复制代码
|
|