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