WIN32 SDK - 捕獲滑鼠離開和滯留等事件 (轉)

worldblog發表於2007-12-09
WIN32 SDK - 捕獲滑鼠離開和滯留等事件 (轉)[@more@]

文章難易程度:初級

首先要了解 TrackMouseEvent  ;

此函式當滑鼠指標離開或在特定時間內盤旋(滯留)在窗體時投遞訊息。引數指向 TRACKMOUSEEVENT 結構體。(詳細定義及解釋請查閱MSDN文件)

typedef struct tagTRACKMOUSEEVENT { D cbSize; //TRACKMOUSEEVENT size. DWORD dwFlags; //Specifies the services requested. HWND hWndtrack; //Specifies a handle to the window to track. DWORD dwHovertime; //hover time-out. } TRACKMOUSEEVENT, *LPTRACKMOUSEEVENT;


以下是原碼:(注意要在屬性頁中連結器的匯入庫中加入 comctl32.lib )


//FileName: MouseLevel.c


#include <.h>
#include //必須匯入此頭



#ifndef APP_NAME
#define APP_NAME TEXT("My MouseHover test")
#endif



const int SUCCEED =0;


ATOM RegisterFormClass(HINSTANCE);
BOOL InitInstance(HINSTANCE,int);
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);



int ENTRY WinMain(HINSTANCE hInstance,
  HINSTANCE hPrevInstance,
  LPSTR lpCmdLine,
    int iCmdShow)
{
 MSG msg; 
 
 
 RegisterFormClass(hInstance);
 if(!InitInstance(hInstance,iCmdShow))
 return FALSE;
 
 while(GetMessage(&msg,NULL,0,0))
 {
 TranslateMessage(&msg);
 DispatchMessage(&msg);
 }
 
 return SUCCEED;
}


ATOM RegisterFormClass(HINSTANCE hInstance)
{
 WNDCLASSEX wcex;
 
 wcex.cbSize = sizeof(WNDCLASSEX);
 wcex.cbClsExtra = 0;
 wcex.cbWndExtra = 0;
 wcex.hbrBackground = (HBRUSH) GetStock(WHITE_BRUSH);
 wcex.hCursor = LoadCursor(NULL,IDC_ARROW);
 wcex.hIcon = LoadIcon(hInstance,IDI_APPLICATION);
 wcex.hIconSm = LoadIcon(NULL,IDI_APPLICATION);
 wcex.hInstance = hInstance;
 wcex.lpfnWndProc = WndProc;
 wcex.lpszClassName = APP_NAME;
 wcex.lpszMenuName = NULL;
 wcex.style = CS_HREDRAW | CS_VREDRAW;
 
 return RegisterClassEx(&wcex);
}


BOOL InitInstance(HINSTANCE hInstance,int iCmdShow)
{
 HWND hWnd;
 
 hWnd = CreateWindowEx(WS_EX_APPWINDOW,
 APP_NAME,
 APP_NAME,
 WS_OVERLAPPEDWINDOW,
 CW_USEDEFAULT,
 CW_USEDEFAULT,
 CW_USEDEFAULT,
 CW_USEDEFAULT,
 NULL,
 NULL,
 hInstance,
 NULL);
 if (!hWnd)
 return FALSE;
 
 ShowWindow(hWnd,iCmdShow);
 UpdateWindow(hWnd);
 
 
 return TRUE;
}


LRESULT CALLBACK WndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
 switch(uMsg)
 {
 case WM_MOUSELEAVE:
 MessageBox(hWnd,TEXT("MouseLeave!"),TEXT("MouseLeave"),0);
 break;
 case WM_MOUSEHOVER:
 MessageBox(hWnd,TEXT("MouseHover"),TEXT("MouseHover"),0);
 break;
 case WM_NCMOUSELEAVE:
 MessageBox(hWnd,TEXT("MouseNClient!"),TEXT("MouseNClient!"),0);
 break;
 case WM_MOUSEMOVE: //因為 TRACKMOUSEEVENT 只傳送一次訊息,且隨著其它訊息產生而失效,所以在此訊息中函式。


 TRACKMOUSEEVENT trmouse;
 trmouse.cbSize = sizeof(TRACKMOUSEEVENT);
 trmouse.dwFlags = TME_LEAVE | TME_HOVER | TME_NONCLIENT;
 trmouse.dwHoverTime = 2000;
 trmouse.hwndTrack = hWnd;
 
 if(!_TrackMouseEvent(&trmouse))
 return FALSE;
 
 break;
 
 case WM_DESTROY:
 PostQuitMessage(0);
 break;
 default:
 return DefWindowProc(hWnd,uMsg,wParam,lParam);
 break;
 }
 return SUCCEED;
}


//此檔案是純 SDK 編寫,不需要MFC等支援。可在DOS下編譯。在WINDOWS98,2000下,VC6,VC7 BETA2中均編譯透過且正確。


 


 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-990191/,如需轉載,請註明出處,否則將追究法律責任。

相關文章