1 // Copyright 2013 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_MESSAGE_WINDOW_H_
6 #define BASE_WIN_MESSAGE_WINDOW_H_
7 
8 #include <windows.h>
9 
10 #include "base/base_export.h"
11 #include "base/callback.h"
12 #include "base/compiler_specific.h"
13 #include "base/macros.h"
14 #include "base/strings/string16.h"
15 #include "base/threading/thread_checker.h"
16 
17 namespace base {
18 namespace win {
19 
20 // Implements a message-only window.
21 class BASE_EXPORT MessageWindow {
22  public:
23   // Used to register a process-wide message window class.
24   class WindowClass;
25 
26   // Implement this callback to handle messages received by the message window.
27   // If the callback returns |false|, the first four parameters are passed to
28   // DefWindowProc(). Otherwise, |*result| is returned by the window procedure.
29   using MessageCallback = base::RepeatingCallback<
30       bool(UINT message, WPARAM wparam, LPARAM lparam, LRESULT* result)>;
31 
32   MessageWindow();
33   ~MessageWindow();
34 
35   // Creates a message-only window. The incoming messages will be passed by
36   // |message_callback|. |message_callback| must outlive |this|.
37   bool Create(MessageCallback message_callback);
38 
39   // Same as Create() but assigns the name to the created window.
40   bool CreateNamed(MessageCallback message_callback,
41                    const string16& window_name);
42 
hwnd()43   HWND hwnd() const { return window_; }
44 
45   // Retrieves a handle of the first message-only window with matching
46   // |window_name|.
47   static HWND FindWindow(const string16& window_name);
48 
49  private:
50   // Give |WindowClass| access to WindowProc().
51   friend class WindowClass;
52 
53   // Contains the actual window creation code.
54   bool DoCreate(MessageCallback message_callback, const wchar_t* window_name);
55 
56   // Invoked by the OS to process incoming window messages.
57   static LRESULT CALLBACK WindowProc(HWND hwnd,
58                                      UINT message,
59                                      WPARAM wparam,
60                                      LPARAM lparam);
61 
62   // Invoked to handle messages received by the window.
63   MessageCallback message_callback_;
64 
65   // Handle of the input window.
66   HWND window_ = nullptr;
67 
68   THREAD_CHECKER(thread_checker_);
69 
70   DISALLOW_COPY_AND_ASSIGN(MessageWindow);
71 };
72 
73 }  // namespace win
74 }  // namespace base
75 
76 #endif  // BASE_WIN_MESSAGE_WINDOW_H_
77