scoped_hdc.h 1.8 KB

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