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