Get the Desktop Device Context

This tip shows how to get a device context handle to the Desktop, which you can then use to draw directly onto the desktop. The sample code doesn't do very much, it just tests the desktop handle by writing some text on it in the top left hand corner.

Start a new project in VB. Add a new module, and add the following code:

Option Explicit 

Private Declare Function CreateDCAsNull Lib "gdi32" Alias "CreateDCA" ( _
    ByVal lpDriverName As String, lpDeviceName As Any, _
    lpOutput As Any, lpInitData As Any) As Long 
Private Declare Function DeleteDC Lib "gdi32" (ByVal hdc As Long) As Long 

Private Type RECT 
    Left As Long 
    Top As Long 
    Right As Long 
    Bottom As Long 
End Type 
Private Declare Function DrawText Lib "user32" Alias "DrawTextA" ( _
    ByVal hdc As Long, ByVal lpStr As String, ByVal nCount As Long, _
    lpRect As RECT, ByVal wFormat As Long) As Long 
Private Declare Function GetTextColor Lib "gdi32" ( _
    ByVal hdc As Long) As Long 
Private Declare Function SetTextColor Lib "gdi32" ( _
    ByVal hdc As Long, ByVal crColor As Long) As Long 

Public Sub TestDesktopDC() 
Dim hdc As Long 
Dim tR As RECT 
Dim lCol As Long 

    ' First get the Desktop DC: 
    hdc = CreateDCAsNull("DISPLAY", ByVal 0&, ByVal 0&, ByVal 0&) 
            
    ' Draw text on it: 
    tR.Left = 0 
    tR.Top = 0 
    tR.Right = 640 
    tR.Bottom = 32 
    lCol = GetTextColor(hdc) 
    SetTextColor hdc, &HFF&
    DrawText hdc, "vbAccelerator", Len("vbAccelerator"), tR, 0 
    SetTextColor hdc, lCol 
    
    ' Make sure you do this to release the GDI 
    ' resource: 
    DeleteDC hdc 
    
End Sub 

To test the code, add a command button to the project's form, and place the following code in it's click event:

Private Sub Command1_Click() 
    TestDesktopDC 
End Sub 

When you click the button, the text vbAccelerator will be written out to the top left hand corner, regardless of whether there are windows covering that area or not.