OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2012 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 #include "ui/base/win/singleton_hwnd.h" |
| 6 |
| 7 #include "base/bind.h" |
| 8 #include "base/callback.h" |
| 9 #include "base/logging.h" |
| 10 #include "base/win/wrapped_window_proc.h" |
| 11 #include "ui/base/win/hwnd_util.h" |
| 12 |
| 13 namespace { |
| 14 |
| 15 // Windows class name to use for the listener window. |
| 16 const wchar_t kWindowClassName[] = L"SingletonHwnd"; |
| 17 |
| 18 // Windows callback for listening for WM_* messages. |
| 19 LRESULT CALLBACK ListenerWindowProc(HWND hwnd, |
| 20 UINT message, |
| 21 WPARAM wparam, |
| 22 LPARAM lparam) { |
| 23 ui::SingletonHwnd::GetInstance()->OnWndProc(hwnd, message, wparam, lparam); |
| 24 return ::DefWindowProc(hwnd, message, wparam, lparam); |
| 25 } |
| 26 |
| 27 // Creates a listener window to receive WM_* messages. |
| 28 HWND CreateListenerWindow() { |
| 29 HINSTANCE hinst = 0; |
| 30 if (!::GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, |
| 31 reinterpret_cast<char*>(&ListenerWindowProc), |
| 32 &hinst)) { |
| 33 NOTREACHED(); |
| 34 } |
| 35 |
| 36 WNDCLASSEX wc = {0}; |
| 37 wc.cbSize = sizeof(wc); |
| 38 wc.lpfnWndProc = base::win::WrappedWindowProc<ListenerWindowProc>; |
| 39 wc.hInstance = hinst; |
| 40 wc.lpszClassName = kWindowClassName; |
| 41 ATOM clazz = ::RegisterClassEx(&wc); |
| 42 DCHECK(clazz); |
| 43 |
| 44 return ::CreateWindow(MAKEINTATOM(clazz), 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, |
| 45 hinst, 0); |
| 46 } |
| 47 |
| 48 } // namespace |
| 49 |
| 50 namespace ui { |
| 51 |
| 52 // static |
| 53 SingletonHwnd* SingletonHwnd::GetInstance() { |
| 54 return Singleton<SingletonHwnd>::get(); |
| 55 } |
| 56 |
| 57 void SingletonHwnd::RegisterListener(WndProcCallback& callback) { |
| 58 if (!listener_window_) { |
| 59 listener_window_ = CreateListenerWindow(); |
| 60 ui::CheckWindowCreated(listener_window_); |
| 61 } |
| 62 listeners_.push_back(callback); |
| 63 } |
| 64 |
| 65 void SingletonHwnd::OnWndProc(HWND hwnd, |
| 66 UINT message, |
| 67 WPARAM wparam, |
| 68 LPARAM lparam) { |
| 69 for (size_t i = 0; i < listeners_.size(); ++i) |
| 70 listeners_[i].Run(hwnd, message, wparam, lparam); |
| 71 } |
| 72 |
| 73 SingletonHwnd::SingletonHwnd() |
| 74 : listener_window_(NULL) { |
| 75 } |
| 76 |
| 77 SingletonHwnd::~SingletonHwnd() { |
| 78 if (listener_window_) { |
| 79 ::DestroyWindow(listener_window_); |
| 80 ::UnregisterClass(kWindowClassName, GetModuleHandle(NULL)); |
| 81 } |
| 82 } |
| 83 |
| 84 } // namespace ui |
OLD | NEW |