11

我有一个具有and的Window元素,因此它没有标题栏并支持透明度。WindowStyle="None"AllowsTransparency="True"

我希望用户能够通过左键单击窗口内的任意位置并拖动来将窗口移动到屏幕上的任何位置。只要按下鼠标左键,窗口就会随着鼠标一起拖动。

我能够使此功能与一个例外一起工作:当鼠标移出窗口时(例如,当在窗口边缘附近按下鼠标左键并且鼠标快速移动时),窗口不再捕获鼠标位置,不随鼠标拖动。

这是我用来完成工作的代码隐藏代码:

public Point MouseDownPosition { get; set; }
public Point MousePosition { get; set; }
public bool MouseIsDown { get; set; }

private void window_MyWindowName_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    MouseDownPosition = e.GetPosition(null);
    MouseIsDown = true;
}

private void window_MyWindowName_MouseMove(object sender, MouseEventArgs e)
{
    if (MouseIsDown)
    {
        MousePosition = e.GetPosition(null);
        Left += MousePosition.X - MouseDownPosition.X;
        Top += MousePosition.Y - MouseDownPosition.Y;
    }
}

private void window_MyWindowName_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    MouseIsDown = false;
}
4

3 回答 3

9

我想你正在寻找这个:Processing Global Mouse and Keyboard Hooks in C#

网址:在 C# 中处理全局鼠标和键盘挂钩

此类允许您点击键盘和鼠标和/或检测它们的活动,即使应用程序在后台运行或根本没有任何用户界面。

此类使用 KeyEventArgs 和 MouseEventArgs 引发常见的 .NET 事件,因此您可以轻松检索所需的任何信息。

有一个例子和解释和演示使用。

很棒的教程!

例子:

UserActivityHook actHook;
void MainFormLoad(object sender, System.EventArgs e)
{
    actHook= new UserActivityHook(); // crate an instance

    // hang on events

    actHook.OnMouseActivity+=new MouseEventHandler(MouseMoved);
    actHook.KeyDown+=new KeyEventHandler(MyKeyDown);
    actHook.KeyPress+=new KeyPressEventHandler(MyKeyPress);
    actHook.KeyUp+=new KeyEventHandler(MyKeyUp);
}

现在,一个如何处理事件的示例:

public void MouseMoved(object sender, MouseEventArgs e)
{
    labelMousePosition.Text=String.Format("x={0}  y={1}", e.X, e.Y);
    if (e.Clicks>0) LogWrite("MouseButton     - " + e.Button.ToString());
}
于 2012-12-05T21:03:57.847 回答
6

我相信你正在重新发明轮子。搜索“Window.DragMove”。

例子:

    private void title_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        this.DragMove();
    }
于 2012-12-05T20:45:38.053 回答
0

试试这种方式:

// method to convert from 'old' WinForms Point to 'new' WPF Point structure:
public System.Windows.Point ConvertToPoint(System.Drawing.Point p)
{
    return new System.Windows.Point(p.X,p.Y);
}

// some locals you will need:
bool mid = false; // Mouse Is Down
int x=0, y=0;

// Mouse down event
private void MainForm_MouseDown(object sender, MouseButtonEventArgs e)
{
   mid=true;
   Point p =  e.GetPosition(this);

   x = (int)p.X; 
   y = (int)p.Y;
}

// Mouse move event
private void MainForm_MouseMove(object sender, MouseButtonEventArgs e)
{
   if(mid)
   {
        int x1 = e.GetPosition(this).X;
        int y1 = e.GetPosition(this).Y;

        Left = x1-x;
        Top = y1-y;
   }
}

// Mouse up event
private void MainForm_MouseUp(object sender, MouseButtonEventArgs e)
{
    mid = false;
}
于 2013-12-03T20:41:53.650 回答