文章难易程度:初级
首先要了解 TrackMouseEvent 函数;
此函数当鼠标指针离开或在特定时间内盘旋(滞留)在窗体时投递消息。参数指向 TRACKMOUSEEVENT 结构体。(详细定义及解释请查阅MSDN文档)
typedef struct tagTRACKMOUSEEVENT { DWORD 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
#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 APIENTRY 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) GetStockObject(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;
}
//此文件是纯 WIN32 SDK 编写,不需要MFC等支持。可在DOS模式下编译。在WINDOWS98,2000下,VC6,VC7 BETA2中均编译通过且正确执行。