Click here to Skip to main content
15,895,799 members
Articles / Programming Languages / C++

Auto Wait Cursor

Rate me:
Please Sign up or sign in to vote.
4.25/5 (15 votes)
31 Dec 20014 min read 125.4K   1.5K   47  
Automate changing the mouse cursor to the hourglass wait cursor.
class AutoWaitCursor
	{
public:
	AutoWaitCursor()
		{
		if (main_threadid == 0)
			{
			main_threadid = GetCurrentThreadId();
			DWORD threadid = 0;
			CreateThread(NULL, 1000, timer_thread, 0, 0, &threadid);
			prev_hook = SetWindowsHookEx(WH_GETMESSAGE, getmessage_hook, 0, main_threadid);
			}

		ticks = 5; // start the timer
		prev_cursor = 0;
		}
	~AutoWaitCursor()
		{
		ticks = 0; // stop timer
		if (prev_cursor)
			{
			// restore cursor
			POINT pt;
			GetCursorPos(&pt);
			SetCursorPos(pt.x, pt.y);
			}
		}
private:
	static DWORD WINAPI timer_thread(LPVOID lpParameter)
		{
		HCURSOR wait_cursor = LoadCursor(NULL, IDC_WAIT);
		// according to MSDN, need to do API call before AttachThreadInput
		AttachThreadInput(GetCurrentThreadId(), main_threadid, true);
		for (;;)
			{
			Sleep(25); // milliseconds
			if (ticks > 0 && --ticks == 0)
				{
				prev_cursor = SetCursor(wait_cursor);
				}
			}
		}
	static LRESULT CALLBACK getmessage_hook(int code, WPARAM wParam, LPARAM lParam)
		{
		ticks = 0; // stop timer
		return CallNextHookEx(prev_hook, code, wParam, lParam);
		}	
	static DWORD main_threadid;
	static HHOOK prev_hook;
	static int volatile ticks;
	static HCURSOR volatile prev_cursor;
	};
DWORD AutoWaitCursor::main_threadid = 0;
HHOOK AutoWaitCursor::prev_hook = 0;
int volatile AutoWaitCursor::ticks = 0;
HCURSOR volatile AutoWaitCursor::prev_cursor = 0;

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Canada Canada
I've been programming for 25 years, first in C and then in C++. I'm a fan of design patterns and agile methodologies like extreme programming. My interests include language and database design, and memory management and garbage collection. The last few years I have been working more or less full time on the open source Suneido project.

Comments and Discussions