How can I capture mouse events that occur outside of a (WPF) window?

廉价感情. 提交于 2019-11-29 04:03:02

I believe you are reinventing the wheel. Search for "Window.DragMove".

Example:

    private void title_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        this.DragMove();
    }

I think you are looking for this: Processing Global Mouse and Keyboard Hooks in C#

Url: Processing Global Mouse and Keyboard Hooks in C#

This class allows you to tap keyboard and mouse and/or to detect their activity even when an application runs in the background or does not have any user interface at all.

This class raises common .NET events with KeyEventArgs and MouseEventArgs, so you can easily retrieve any information you need.

There is an example and explain and demo to use.

Great tutorial!

Example:

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);
}

Now, an example of how to process an event:

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());
}

Try it this way:

// 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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!