scoped_gdi_object.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef MODULES_DESKTOP_CAPTURE_WIN_SCOPED_GDI_HANDLE_H_
  11. #define MODULES_DESKTOP_CAPTURE_WIN_SCOPED_GDI_HANDLE_H_
  12. #include <windows.h>
  13. #include "rtc_base/constructor_magic.h"
  14. namespace webrtc {
  15. namespace win {
  16. // Scoper for GDI objects.
  17. template <class T, class Traits>
  18. class ScopedGDIObject {
  19. public:
  20. ScopedGDIObject() : handle_(NULL) {}
  21. explicit ScopedGDIObject(T object) : handle_(object) {}
  22. ~ScopedGDIObject() { Traits::Close(handle_); }
  23. T Get() { return handle_; }
  24. void Set(T object) {
  25. if (handle_ && object != handle_)
  26. Traits::Close(handle_);
  27. handle_ = object;
  28. }
  29. ScopedGDIObject& operator=(T object) {
  30. Set(object);
  31. return *this;
  32. }
  33. T release() {
  34. T object = handle_;
  35. handle_ = NULL;
  36. return object;
  37. }
  38. operator T() { return handle_; }
  39. private:
  40. T handle_;
  41. RTC_DISALLOW_COPY_AND_ASSIGN(ScopedGDIObject);
  42. };
  43. // The traits class that uses DeleteObject() to close a handle.
  44. template <typename T>
  45. class DeleteObjectTraits {
  46. public:
  47. DeleteObjectTraits() = delete;
  48. DeleteObjectTraits(const DeleteObjectTraits&) = delete;
  49. DeleteObjectTraits& operator=(const DeleteObjectTraits&) = delete;
  50. // Closes the handle.
  51. static void Close(T handle) {
  52. if (handle)
  53. DeleteObject(handle);
  54. }
  55. };
  56. // The traits class that uses DestroyCursor() to close a handle.
  57. class DestroyCursorTraits {
  58. public:
  59. DestroyCursorTraits() = delete;
  60. DestroyCursorTraits(const DestroyCursorTraits&) = delete;
  61. DestroyCursorTraits& operator=(const DestroyCursorTraits&) = delete;
  62. // Closes the handle.
  63. static void Close(HCURSOR handle) {
  64. if (handle)
  65. DestroyCursor(handle);
  66. }
  67. };
  68. typedef ScopedGDIObject<HBITMAP, DeleteObjectTraits<HBITMAP> > ScopedBitmap;
  69. typedef ScopedGDIObject<HCURSOR, DestroyCursorTraits> ScopedCursor;
  70. } // namespace win
  71. } // namespace webrtc
  72. #endif // MODULES_DESKTOP_CAPTURE_WIN_SCOPED_GDI_HANDLE_H_