Home | History | Annotate | Download | only in win
      1 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef BASE_WIN_SCOPED_GDI_OBJECT_H_
      6 #define BASE_WIN_SCOPED_GDI_OBJECT_H_
      7 #pragma once
      8 
      9 #include <windows.h>
     10 
     11 #include "base/basictypes.h"
     12 #include "base/logging.h"
     13 
     14 namespace base {
     15 namespace win {
     16 
     17 // Like ScopedHandle but for GDI objects.
     18 template<class T>
     19 class ScopedGDIObject {
     20  public:
     21   ScopedGDIObject() : object_(NULL) {}
     22   explicit ScopedGDIObject(T object) : object_(object) {}
     23 
     24   ~ScopedGDIObject() {
     25     Close();
     26   }
     27 
     28   T Get() {
     29     return object_;
     30   }
     31 
     32   void Set(T object) {
     33     if (object_ && object != object_)
     34       Close();
     35     object_ = object;
     36   }
     37 
     38   ScopedGDIObject& operator=(T object) {
     39     Set(object);
     40     return *this;
     41   }
     42 
     43   T release() {
     44     T object = object_;
     45     object_ = NULL;
     46     return object;
     47   }
     48 
     49   operator T() { return object_; }
     50 
     51  private:
     52   void Close() {
     53     if (object_)
     54       DeleteObject(object_);
     55   }
     56 
     57   T object_;
     58   DISALLOW_COPY_AND_ASSIGN(ScopedGDIObject);
     59 };
     60 
     61 // An explicit specialization for HICON because we have to call DestroyIcon()
     62 // instead of DeleteObject() for HICON.
     63 template<>
     64 void ScopedGDIObject<HICON>::Close() {
     65   if (object_)
     66     DestroyIcon(object_);
     67 }
     68 
     69 // Typedefs for some common use cases.
     70 typedef ScopedGDIObject<HBITMAP> ScopedBitmap;
     71 typedef ScopedGDIObject<HRGN> ScopedRegion;
     72 typedef ScopedGDIObject<HFONT> ScopedHFONT;
     73 typedef ScopedGDIObject<HICON> ScopedHICON;
     74 
     75 }  // namespace win
     76 }  // namespace base
     77 
     78 #endif  // BASE_WIN_SCOPED_GDI_OBJECT_H_
     79