summaryrefslogtreecommitdiff
path: root/base/win/scoped_hdc.h
blob: 890e34a82c5b0dfa8d82964f6c4b69fdf7d331d6 (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
78
// Copyright (c) 2012 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_HDC_H_
#define BASE_WIN_SCOPED_HDC_H_

#include <windows.h>

#include "base/debug/gdi_debug_util_win.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/win/scoped_handle.h"

namespace base {
namespace win {

// Like ScopedHandle but for HDC.  Only use this on HDCs returned from
// GetDC.
class ScopedGetDC {
 public:
  explicit ScopedGetDC(HWND hwnd)
      : hwnd_(hwnd),
        hdc_(GetDC(hwnd)) {
    if (hwnd_) {
      DCHECK(IsWindow(hwnd_));
      DCHECK(hdc_);
    } else {
      // If GetDC(NULL) returns NULL, something really bad has happened, like
      // GDI handle exhaustion.  In this case Chrome is going to behave badly no
      // matter what, so we may as well just force a crash now.
      if (!hdc_)
        base::debug::CollectGDIUsageAndDie();
    }
  }

  ~ScopedGetDC() {
    if (hdc_)
      ReleaseDC(hwnd_, hdc_);
  }

  operator HDC() { return hdc_; }

 private:
  HWND hwnd_;
  HDC hdc_;

  DISALLOW_COPY_AND_ASSIGN(ScopedGetDC);
};

// Like ScopedHandle but for HDC.  Only use this on HDCs returned from
// CreateCompatibleDC, CreateDC and CreateIC.
class CreateDCTraits {
 public:
  typedef HDC Handle;

  static bool CloseHandle(HDC handle) {
    return ::DeleteDC(handle) != FALSE;
  }

  static bool IsHandleValid(HDC handle) {
    return handle != NULL;
  }

  static HDC NullHandle() {
    return NULL;
  }

 private:
  DISALLOW_IMPLICIT_CONSTRUCTORS(CreateDCTraits);
};

typedef GenericScopedHandle<CreateDCTraits, DummyVerifierTraits> ScopedCreateDC;

}  // namespace win
}  // namespace base

#endif  // BASE_WIN_SCOPED_HDC_H_