hdc1 = GetDC(hWnd);
hdc2 = GetDC(hWnd);
hdc3 = GetDC(hWnd);
hdc4 = GetDC(hWnd);断点跟踪,发现hdc1、hdc2、hdc3、hdc4的数值都不一样,为什么呀?

解决方案 »

  1.   

    这跟窗口类有关系,如果窗口类的样式中含有CS_OWNDC,则GetDC的值不变,否则,由Windows临时分配。
      

  2.   

    Classes and Device Contexts
    A device context is a special set of values that applications use for drawing in the client area of their windows. The system requires a device context for each window on the display but allows some flexibility in how the system stores and treats that device context.If no device-context style is explicitly given, the system assumes each window uses a device context retrieved from a pool of contexts maintained by the system. In such cases, each window must retrieve and initialize the device context before painting and free it after painting.To avoid retrieving a device context each time it needs to paint inside a window, an application can specify the CS_OWNDC style for the window class. This class style directs the system to create a private device context — that is, to allocate a unique device context for each window in the class. The application need only retrieve the context once and then use it for all subsequent painting.MSDN里的话 看看最后一段
      

  3.   

    If no device-context style is explicitly given, the system assumes each window uses a device context retrieved from a pool of contexts maintained by the system.
      

  4.   

    DC作为系统资源是有限的,不可能为每个窗口分配一个独立的DC,应用程序也不应该长期保存从窗口获得的DC,大多数标准控件窗口都共享父窗口的DC(用SPY++看看控件窗口的类属性就知道,基本上都有PARENTDC的类样式)。
    早期WINDOWS版本的应用程序只有4个DC资源供调度,2000开始虽然大大扩充了这个数量,但对比窗口数量来说还是属于稀缺资源。窗口创建时可通过在窗口类中指定标志来决定如何使用DC,可以是系统分配、独占一个DC、共享父窗口DC等等。如果是独占DC(OWNDC),则可以长期保存GetDC获得的HDC,无需中途释放且一直有效。CLASSDC表示某一类窗口共享一个DC,其它类型类似,看名称即可理解,这些DC不是独占的,不能长期霸占其句柄,应该在一个消息周期内获取和释放,且每次获取的DC句柄可能是不同的。