scoped_gdi_object.h (2365B)
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 11 #ifndef MODULES_DESKTOP_CAPTURE_WIN_SCOPED_GDI_HANDLE_H_ 12 #define MODULES_DESKTOP_CAPTURE_WIN_SCOPED_GDI_HANDLE_H_ 13 14 #include <windows.h> 15 16 #include <cstddef> 17 18 namespace webrtc { 19 namespace win { 20 21 // Scoper for GDI objects. 22 template <class T, class Traits> 23 class ScopedGDIObject { 24 public: 25 ScopedGDIObject() : handle_(NULL) {} 26 explicit ScopedGDIObject(T object) : handle_(object) {} 27 28 ~ScopedGDIObject() { Traits::Close(handle_); } 29 30 ScopedGDIObject(const ScopedGDIObject&) = delete; 31 ScopedGDIObject& operator=(const ScopedGDIObject&) = delete; 32 33 T Get() { return handle_; } 34 35 void Set(T object) { 36 if (handle_ && object != handle_) 37 Traits::Close(handle_); 38 handle_ = object; 39 } 40 41 ScopedGDIObject& operator=(T object) { 42 Set(object); 43 return *this; 44 } 45 46 T release() { 47 T object = handle_; 48 handle_ = NULL; 49 return object; 50 } 51 52 operator T() { return handle_; } 53 54 private: 55 T handle_; 56 }; 57 58 // The traits class that uses DeleteObject() to close a handle. 59 template <typename T> 60 class DeleteObjectTraits { 61 public: 62 DeleteObjectTraits() = delete; 63 DeleteObjectTraits(const DeleteObjectTraits&) = delete; 64 DeleteObjectTraits& operator=(const DeleteObjectTraits&) = delete; 65 66 // Closes the handle. 67 static void Close(T handle) { 68 if (handle) 69 DeleteObject(handle); 70 } 71 }; 72 73 // The traits class that uses DestroyCursor() to close a handle. 74 class DestroyCursorTraits { 75 public: 76 DestroyCursorTraits() = delete; 77 DestroyCursorTraits(const DestroyCursorTraits&) = delete; 78 DestroyCursorTraits& operator=(const DestroyCursorTraits&) = delete; 79 80 // Closes the handle. 81 static void Close(HCURSOR handle) { 82 if (handle) 83 DestroyCursor(handle); 84 } 85 }; 86 87 typedef ScopedGDIObject<HBITMAP, DeleteObjectTraits<HBITMAP> > ScopedBitmap; 88 typedef ScopedGDIObject<HCURSOR, DestroyCursorTraits> ScopedCursor; 89 90 } // namespace win 91 } // namespace webrtc 92 93 #endif // MODULES_DESKTOP_CAPTURE_WIN_SCOPED_GDI_HANDLE_H_