使用 C# 将点击发送到背景 window 在面板中的相对位置

Send click to background window relative position in panel with C#

我使用 C#,我有一个带有按钮 1、按钮 2 和面板 1 的应用程序,如果我单击按钮 1,它会打开一个外部程序到面板 1,然后如果我单击按钮 2,它会向 window,工作正常。 但问题是这个点击位置不是相对于面板的,也没有去到正确的地方。它会将点击发送到光标实际所在的位置。

我使用的代码片段:

PerformRightClick(proc.MainWindowHandle, new Point(54, 42));
void PerformRightClick(IntPtr hwnd, Point point)
{
     var pointPtr = MakeLParam(point.X, point.Y);
     SendMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, pointPtr);
     SendMessage(hwnd, WM_RBUTTONDOWN, IntPtr.Zero, pointPtr);
     SendMessage(hwnd, WM_RBUTTONUP, IntPtr.Zero, pointPtr);
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
IntPtr MakeLParam(int x, int y) => (IntPtr)((y << 16) | (x & 0xFFFF));

根据我的测试,当我们想要将点击发送到面板时,我们需要使用 panel.Handle

这是一个代码示例,您可以参考。

private const Int32 WM_MOUSEMOVE = 0x0200;

        private const Int32 WM_RBUTTONDOWN = 0x0204;
        private const Int32 WM_RBUTTONUP = 0x0205;
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
        IntPtr MakeLParam(int x, int y) => (IntPtr)((y << 16) | (x & 0xFFFF));

        private void button1_Click(object sender, EventArgs e)
        {
            PerformRightClick(panel1.Handle, new Point(20, 30));
        }

        void PerformRightClick(IntPtr hwnd, Point point)
        {
            var pointPtr = MakeLParam(point.X, point.Y);
            SendMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, pointPtr);
            SendMessage(hwnd, WM_RBUTTONDOWN, IntPtr.Zero, pointPtr);
            SendMessage(hwnd, WM_RBUTTONUP, IntPtr.Zero, pointPtr);
        }

        private void panel1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Panel is clicked");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PerformRightClick(this.Handle, new Point(20, 30));
        }

        private void Form1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Form is clicked");
        }

图片:

如上图,当我们点击button1时,点击的是panel,点击button2时点击的是Form。