summaryrefslogtreecommitdiffstats
path: root/base/win/scoped_gdi_object.h
blob: d44310a159857073e80f2b90d73ba367f0c4ce3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_WIN_SCOPED_GDI_OBJECT_H_
#define BASE_WIN_SCOPED_GDI_OBJECT_H_

#include <windows.h>

#include "base/basictypes.h"
#include "base/logging.h"

namespace base {
namespace win {

// Like ScopedHandle but for GDI objects.
template<class T>
class ScopedGDIObject {
 public:
  ScopedGDIObject() : object_(NULL) {}
  explicit ScopedGDIObject(T object) : object_(object) {}

  ~ScopedGDIObject() {
    Close();
  }

  T Get() {
    return object_;
  }

  void Set(T object) {
    if (object_ && object != object_)
      Close();
    object_ = object;
  }

  ScopedGDIObject& operator=(T object) {
    Set(object);
    return *this;
  }

  T release() {
    T object = object_;
    object_ = NULL;
    return object;
  }

  operator T() { return object_; }

 private:
  void Close() {
    if (object_)
      DeleteObject(object_);
  }

  T object_;
  DISALLOW_COPY_AND_ASSIGN(ScopedGDIObject);
};

// An explicit specialization for HICON because we have to call DestroyIcon()
// instead of DeleteObject() for HICON.
template<>
void ScopedGDIObject<HICON>::Close() {
  if (object_)
    DestroyIcon(object_);
}

// Typedefs for some common use cases.
typedef ScopedGDIObject<HBITMAP> ScopedBitmap;
typedef ScopedGDIObject<HRGN> ScopedRegion;
typedef ScopedGDIObject<HFONT> ScopedHFONT;
typedef ScopedGDIObject<HICON> ScopedHICON;

}  // namespace win
}  // namespace base

#endif  // BASE_WIN_SCOPED_GDI_OBJECT_H_