1 // Copyright (c) 2020 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/event_creation_utils.h"
6 
7 #include <windows.h>
8 #include <winuser.h>
9 
10 #include <algorithm>
11 
12 #include "base/numerics/ranges.h"
13 #include "ui/gfx/geometry/point.h"
14 
15 namespace ui {
16 
SendMouseEvent(const gfx::Point & point,int flags)17 bool SendMouseEvent(const gfx::Point& point, int flags) {
18   INPUT input = {INPUT_MOUSE};
19   // Get the max screen coordinate for use in computing the normalized absolute
20   // coordinates required by SendInput.
21   const int screen_width = ::GetSystemMetrics(SM_CXSCREEN);
22   const int screen_height = ::GetSystemMetrics(SM_CYSCREEN);
23   int screen_x = base::ClampToRange(point.x(), 0, screen_width - 1);
24   int screen_y = base::ClampToRange(point.y(), 0, screen_height - 1);
25 
26   // In normalized absolute coordinates, (0, 0) maps onto the upper-left corner
27   // of the display surface, while (65535, 65535) maps onto the lower-right
28   // corner.
29   // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mouse_event#remarks
30   static constexpr double kNormalizedScreenSize = 65536.0;
31 
32   // Form the input data containing the normalized absolute coordinates. As of
33   // Windows 10 Fall Creators Update, moving to an absolute position of zero
34   // does not work. It seems that moving to 1,1 does, though.
35   input.mi.dx = static_cast<LONG>(std::max(
36       1.0, std::ceil(screen_x * (kNormalizedScreenSize / screen_width))));
37   input.mi.dy = static_cast<LONG>(std::max(
38       1.0, std::ceil(screen_y * (kNormalizedScreenSize / screen_height))));
39   input.mi.dwFlags = flags;
40   return ::SendInput(1, &input, sizeof(input)) == 1;
41 }
42 
43 }  // namespace ui
44