The new vbAccelerator Site - more VB and .NET Code and Controls

Get the Desktop Device Context


Steve McMahon(





Other Tips
All Tips
By Date
By Subject

API (33)
Manipulation (3)

Clipboard (3)
Box (5)

Desktop (3)
GDI (13)
Graphics (13)
Internet (2)
Comms (3)

Keyboard (2)
Mouse (1)
Shell (1)
Sprites (1)
Subclassing (3)
Box (2)

Windows (11)
Controls (10)


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
&nbsp &nbsp Left As Long
&nbsp &nbsp Top As Long
&nbsp &nbsp Right As Long
&nbsp &nbsp 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

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


Related Tips and Articles:


AboutContributeSend FeedbackPrivacy

Copyright 1998-1999, Steve McMahon ( All Rights Reserved.
Last updated: 01/08/98