HOWTO: Obtain A Handle To the Current Cursor

ID: Q230495


The information in this article applies to:
  • Microsoft Win32 Application Programming Interface (API)
  • Microsoft Windows 2000


SUMMARY

The GetCursor() API is limited in that it does not, by default, return a handle to the current cursor when that cursor is owned by another thread. This article demonstrates a way to retrieve the current cursor regardless of what thread owns it; for example, when you wish to include the image of the cursor in a screen capture. Since the cursor is hidden whenever you use GDI operations to read or write from the screen, you need to explicitly draw the cursor into a screen capture if you want it included. With the code in this article, you can obtain a handle to the current cursor and then use the DrawIcon() API to draw it into the screen capture at the appropriate coordinates.


MORE INFORMATION

<BR/>
/**********************************************************

GetCurrentCursorHandle
  
  Purpose:
    Retrieves a handle to the current cursor regardless of 
    whether or not it's owned by the current thread. This is 
    useful, for example, when you need to draw the image
    of the current cursor into a screen capture using 
    DrawIcon().
    
  Input:
    <none>
      
  Return:
    The return value is the handle to the current cursor. 
    If there is no cursor, the return value is NULL. 
    
  Notes:
    Windows NT: This function cannot be used to capture the
	cursor on another desktop.
          
**********************************************************/ 
HCURSOR GetCurrentCursorHandle()
{
    POINT pt;
    HWND hWnd;        
    DWORD dwThreadID, dwCurrentThreadID;
    HCURSOR hCursor = NULL;
    
    // Find out which window owns the cursor
    GetCursorPos(&pt);
    hWnd = WindowFromPoint(pt);
    
    // Get the thread ID for the cursor owner.
    dwThreadID = GetWindowThreadProcessId(hWnd, NULL);
    
    // Get the thread ID for the current thread
    dwCurrentThreadID = GetCurrentThreadId();
    
    // If the cursor owner is not us then we must attach to 
    // the other thread in so that we can use GetCursor() to 
    // return the correct hCursor
    if (dwCurrentThreadID != dwThreadID) {
        
        // Attach to the thread that owns the cursor
        if (AttachThreadInput(dwCurrentThreadID, dwThreadID, TRUE)) {
            
            // Get the handle to the cursor
            hCursor = GetCursor();
            
            // Detach from the thread that owns the cursor
            AttachThreadInput(dwCurrentThreadID, dwThreadID, FALSE);
        }
    } else
        hCursor = GetCursor();
    
    return hCursor;
} 

Additional query words:

Keywords : kbGDI kbIcon kbWinOS2000 kbSDKWin32
Version : WINDOWS:; winnt:
Platform : WINDOWS winnt
Issue type : kbhowto


Last Reviewed: December 20, 1999
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.