scoped_hdc.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. #ifndef BASE_WIN_SCOPED_HDC_H_
  5. #define BASE_WIN_SCOPED_HDC_H_
  6. #include <windows.h>
  7. #include "base/check.h"
  8. #include "base/debug/gdi_debug_util_win.h"
  9. #include "base/macros.h"
  10. #include "base/win/scoped_handle.h"
  11. namespace base {
  12. namespace win {
  13. // Like ScopedHandle but for HDC. Only use this on HDCs returned from
  14. // GetDC.
  15. class ScopedGetDC {
  16. public:
  17. explicit ScopedGetDC(HWND hwnd) : hwnd_(hwnd), hdc_(GetDC(hwnd)) {
  18. if (hwnd_) {
  19. DCHECK(IsWindow(hwnd_));
  20. DCHECK(hdc_);
  21. } else {
  22. // If GetDC(NULL) returns NULL, something really bad has happened, like
  23. // GDI handle exhaustion. In this case Chrome is going to behave badly no
  24. // matter what, so we may as well just force a crash now.
  25. if (!hdc_)
  26. base::debug::CollectGDIUsageAndDie();
  27. }
  28. }
  29. ~ScopedGetDC() {
  30. if (hdc_)
  31. ReleaseDC(hwnd_, hdc_);
  32. }
  33. operator HDC() { return hdc_; }
  34. private:
  35. HWND hwnd_;
  36. HDC hdc_;
  37. DISALLOW_COPY_AND_ASSIGN(ScopedGetDC);
  38. };
  39. // Like ScopedHandle but for HDC. Only use this on HDCs returned from
  40. // CreateCompatibleDC, CreateDC and CreateIC.
  41. class CreateDCTraits {
  42. public:
  43. typedef HDC Handle;
  44. static bool CloseHandle(HDC handle) { return ::DeleteDC(handle) != FALSE; }
  45. static bool IsHandleValid(HDC handle) { return handle != NULL; }
  46. static HDC NullHandle() { return NULL; }
  47. private:
  48. DISALLOW_IMPLICIT_CONSTRUCTORS(CreateDCTraits);
  49. };
  50. typedef GenericScopedHandle<CreateDCTraits, DummyVerifierTraits> ScopedCreateDC;
  51. } // namespace win
  52. } // namespace base
  53. #endif // BASE_WIN_SCOPED_HDC_H_