鼠标拖动窗口以编程方式

时间:2016-11-24 14:39:38

标签: c# multiscreen

我正在尝试开发一个程序,它将打开2个Guitar Pro文件,并在我的多屏设置上的不同屏幕上显示它们。

除了将1个窗口从屏幕1移动到屏幕2之外,我已经完成了所有工作。

吉他专业版有点狡猾,出于某种原因只会在屏幕1中打开文件...我试图通过抓住窗口手柄来移动窗口,但这只会移动主容器并使所有子窗口保持不变地点。我决定欺骗它并以编程方式移动鼠标光标以点击并将窗口从屏幕拖动到屏幕,但我仍然遇到问题......

[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

public void OpenFileFn()
    {
    Process file1 = new Process();
    file1.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
    file1.StartInfo.FileName = file;
    file1.Start();
    Thread.Sleep(500);
    Process file2 = new Process();
    file2.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
    file2.StartInfo.FileName = file;
    file2.Start();
    file2.WaitForInputIdle();
    Thread.Sleep(3000);
    int posX = Cursor.Position.X;
    int posY = Cursor.Position.Y;
    SetCursorPos(-960, 15);
    mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
    SetCursorPos(960, 15);
    mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
    SetCursorPos(posX, posY);
    }

使用上面的代码水平移动光标而不是窗口...如果我改变光标Y轴,窗口会垂直移动......

为什么我能解决这个问题的任何想法? 提前谢谢......

1 个答案:

答案 0 :(得分:2)

试试这个:

public class MouseManager
{
    public void MoveCursor(int x, int y)
    {
        Win32.POINT p = new Win32.POINT
        {
            x = x,
            y = y
        };

        Win32.SetCursorPos(p.x, p.y);
    }

    public int GetX()
    {
        var p = Win32.GetCursorPosition();
        return p.x;
    }

    public int GetY()
    {
        var p = Win32.GetCursorPosition();
        return p.y;
    }

    public void Click()
    {
        Win32.MouseEvent(Win32.MouseEventFlags.LeftDown);
        Win32.MouseEvent(Win32.MouseEventFlags.LeftUp);
    }

    public void RightClick()
    {
        Win32.MouseEvent(Win32.MouseEventFlags.RightDown);
        Win32.MouseEvent(Win32.MouseEventFlags.RightUp);
    }

    public void DoubleClick()
    {
        Win32.MouseEvent(Win32.MouseEventFlags.LeftDown);
        Win32.MouseEvent(Win32.MouseEventFlags.LeftUp);
        Win32.MouseEvent(Win32.MouseEventFlags.LeftDown);
        Win32.MouseEvent(Win32.MouseEventFlags.LeftUp);
    }

    public void Scroll(int y)
    {
        Win32.Scroll(y);
    }

    public void ClickDown()
    {
        Win32.MouseEvent(Win32.MouseEventFlags.LeftDown);
    }

    public void ClickUp()
    {
        Win32.MouseEvent(Win32.MouseEventFlags.LeftUp);
    }
}

步骤进行:

  1. 将光标移动到窗口位置

  2. 点击

  3. 再次移动光标以移动窗口

  4. 点击

  5. 步骤进行:

    var manager= new MouseManager();
    manager.MoveCursor(-960,15);
    manager.ClickDown();
    manager.MoveCursor(960,15);
    manager.ClickUp();