scoped_hdc.h revision b8cf94937c52feb53b55c39e3f82094d27de464c
1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#ifndef BASE_WIN_SCOPED_HDC_H_ 6#define BASE_WIN_SCOPED_HDC_H_ 7 8#include <windows.h> 9 10#include "base/basictypes.h" 11#include "base/logging.h" 12#include "base/win/scoped_handle.h" 13 14namespace base { 15namespace win { 16 17// Like ScopedHandle but for HDC. Only use this on HDCs returned from 18// GetDC. 19class ScopedGetDC { 20 public: 21 explicit ScopedGetDC(HWND hwnd) 22 : hwnd_(hwnd), 23 hdc_(GetDC(hwnd)) { 24 if (hwnd_) { 25 DCHECK(IsWindow(hwnd_)); 26 DCHECK(hdc_); 27 } else { 28 // If GetDC(NULL) returns NULL, something really bad has happened, like 29 // GDI handle exhaustion. In this case Chrome is going to behave badly no 30 // matter what, so we may as well just force a crash now. 31 CHECK(hdc_); 32 } 33 } 34 35 ~ScopedGetDC() { 36 if (hdc_) 37 ReleaseDC(hwnd_, hdc_); 38 } 39 40 operator HDC() { return hdc_; } 41 42 private: 43 HWND hwnd_; 44 HDC hdc_; 45 46 DISALLOW_COPY_AND_ASSIGN(ScopedGetDC); 47}; 48 49// Like ScopedHandle but for HDC. Only use this on HDCs returned from 50// CreateCompatibleDC, CreateDC and CreateIC. 51class CreateDCTraits { 52 public: 53 typedef HDC Handle; 54 55 static bool CloseHandle(HDC handle) { 56 return ::DeleteDC(handle) != FALSE; 57 } 58 59 static bool IsHandleValid(HDC handle) { 60 return handle != NULL; 61 } 62 63 static HDC NullHandle() { 64 return NULL; 65 } 66 67 private: 68 DISALLOW_IMPLICIT_CONSTRUCTORS(CreateDCTraits); 69}; 70 71typedef GenericScopedHandle<CreateDCTraits, DummyVerifierTraits> ScopedCreateDC; 72 73} // namespace win 74} // namespace base 75 76#endif // BASE_WIN_SCOPED_HDC_H_ 77