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