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

Jackson Dean Goodwin picture Jackson Dean Goodwin · Dec 5, 2012 · Viewed 13.9k times · Source

I have a Window element that has WindowStyle="None" and AllowsTransparency="True", therefore it has no title bar and supports transparency.

I want the user to be able to move the Window to any position on the screen by left-clicking anywhere within the Window and dragging. The Window should drag along with the mouse as long as the left mouse button is pressed down.

I was able to get this functionality to work with one exception: when the mouse moves outside of the Window (such as when the left mouse button was pressed down near the edge of the Window and the mouse is moved quicly), the Window no longer captures the mouse position and does not drag along with the mouse.

Here is the code from the code-behind that I use to get the job done:

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

Answer

Ofear picture Ofear · Dec 5, 2012

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