| Version: 3.3.1

Device Contexts

A wxDC is a device context onto which graphics and text can be drawn.

The device context is intended to represent a number of output devices in a generic way, with the same API being used throughout.

Objects of wxDC class itself can't be created, instead you should create objects of the following classes:

- wxPaintDC for painting on a window from within a paint event handler. This is the most common device context to use.
- wxMemoryDC for painting off-screen, i.e. to a bitmap.
- wxPrinterDC for printing.
- wxInfoDC for obtaining information about the device context without drawing on it.

To draw on a window, you need to create a wxPaintDC object in the paint event handler:

void MyWindow::OnPaint(wxPaintEvent& event)
{
wxPaintDC dc(this);
dc.DrawText("Hello, world!", 20, 20);
}
wxPaintDC
A wxPaintDC must be constructed if an application wishes to paint on the client area of a window from...
Definition: dcclient.h:30
wxPaintEvent
A paint event is sent when a window's contents needs to be repainted.
Definition: event.h:2321

To obtain information about a device context associated with a window outside of its paint event handler, you need to use wxInfoDC, e.g. the window as argument, for example:

void MyFrame::SomeFunction()
{
wxInfoDC dc(this);
// Create control with the width just big enough for the given string.
auto* text = new wxStaticText
(
this, wxID_ANY, "",
wxPoint(),
dc.GetTextExtent("String of max length"),
wxST_NO_AUTORESIZE
);
}
wxInfoDC
Class used for querying the window device context.
Definition: dc.h:1935
wxPoint
A wxPoint is a useful data structure for graphics operations.
Definition: gdicmn.h:686
wxStaticText
A static text control displays one or more lines of read-only text.
Definition: stattext.h:54
wxID_ANY
@ wxID_ANY
Any id: means that we don't care about the id, whether when installing an event handler or when creat...
Definition: defs.h:591
wxST_NO_AUTORESIZE
#define wxST_NO_AUTORESIZE
Definition: stattext.h:8

When writing drawing code, it is recommended to extract it into a function taking wxDC as an argument. This allows you to reuse the same code for drawing and printing, by calling it with either wxPaintDC or wxPrinterDC.

Please note that other device context classes that could previously be used for painting on screen cannot be used any more due to the architecture of the modern graphics systems. In particular, wxClientDC, wxWindowDC and wxScreenDC are not guaranteed to work any longer.

See also
  Device Contexts