Getting mouse co-ordinates on a mouse click in C# - c#

I want to build myself an application that will run in the background (system tray) and log the co-ordinates of my mouse whenever I click the left or right buttons. I found this code online to get the mouse co-ordinates through an event that triggers:
protected override void OnMouseMove(MouseEventArgs mouseEv)
{
txtMouseX.Text = mouseEv.X.ToString();
txtMouseY.Text = mouseEv.Y.ToString();
}
This points me in the right direction, I now know how I can get the X and Y co-ordinates of the mouse, but I don't know how to trigger a function or whatever on a mouse click if the application is running in the background. Also, it seems that this code only works in the form it is running in, not for the entire screen?
Any help is appreciated, cheers.

You'll need a global hook. Here is a code project article with a library that does what you are looking for: Global Mouse and Keyboard Library

You can use GetCursorPos win32 API to get the position of your Mouse at any time. Here is the sample code for this:-
Dim MyPointAPI As POINTAPI
Private Type POINTAPI
X As Long
Y As Long
End Type
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Public Sub Timer1_Timer()
l = GetCursorPos(MyPointAPI)
Label1.Caption = CStr(MyPointAPI.X) & ", " & CStr(MyPointAPI.Y)
End Sub

Take a look at this library http://globalmousekeyhook.codeplex.com/.
It allows you to track mouse coordinate system wide even if your application is inactive (in tray).

Related

alternate moving /hightlighting a control using x/y postioning

I'm looking for an api that can cause a windows select/highlight event to occur on a windows desktop, without actually causing the mouse cursor to move.. I can cause the mouse cursor to move with :
public static extern bool SetCursorPos(int X, int Y);
But that moves the actual cursor to that point... I'm looking for a way to highlight only as one might do by using the tab and arrow keys to move around the windows desktop. Any suggestions are appreciated..
regards, rob
I think you may be looking for SetFocus. You can get a control's handle with Control.Handle or FindWindow , and p/invoke SetFocus (use IntPtr as the argument type).

KinectRegion HandPointer Cursor as mouse cursor in Awesomium Browser

I would like to use the kinect hand cursor as 'normal' mouse cursor. In the specific I want to be able to interact with the Awesomium browser object.
The problem is that no Awesomium Browser event is raised when the kinect hand cursor is (for example) over a link, or I do a click, or any other typical mouse event.
I modified the Control Basics-WPF example program that you can find in the example directory of the Kinect SDK
I am using c# visual studio 2012, Kinect SDK 1.7, Awesomium 1.7.1.
It's been a month since this question's been asked, so perhaps you've already found your own solution.
In any case, I found myself in this scenario as well, and here was my solution:
Inside MainWindow.xaml, you'll need the Awesomium control inside a KinectRegion (from the SDK).
You'll have to somehow tell the SDK that you want a control to also handle hand events. You can do this by adding this inside MainWindow.xaml.cs on the Window_Loaded handler:
KinectRegion.AddHandPointerMoveHandler(webControl1, OnHandleHandMove);
KinectRegion.AddHandPointerLeaveHandler(webControl1, OnHandleHandLeave);
Elsewhere in MainWindow.xaml.cs, you can define the hand handler events. Incidentally, I did it like this:
private void OnHandleHandLeave(object source, HandPointerEventArgs args)
{
// This just moves the cursor to the top left corner of the screen.
// You can handle it differently, but this is just one way.
System.Drawing.Point mousePt = new System.Drawing.Point(0, 0);
System.Windows.Forms.Cursor.Position = mousePt;
}
private void OnHandleHandMove(object source, HandPointerEventArgs args)
{
// The meat of the hand handle method.
HandPointer ptr = args.HandPointer;
Point newPoint = kinectRegion.PointToScreen(ptr.GetPosition(kinectRegion));
clickIfHandIsStable(newPoint); // basically handle a click, not showing code here
changeMouseCursorPosition(newPoint); // this is where you make the hand and mouse positions the same!
}
private void changeMouseCursorPosition(Point newPoint)
{
cursorPoint = newPoint;
System.Drawing.Point mousePt = new System.Drawing.Point((int)cursorPoint.X, (int)cursorPoint.Y);
System.Windows.Forms.Cursor.Position = mousePt;
}
For me, the tricky parts were:
1. Diving into the SDK and figuring out which handlers to add. Documentation wasn't terribly helpful on this.
2. Mapping the mouse cursor to the kinect hand. As you can see, it involves dealing with System.Drawing.Point (separate from another library's Point) and System.Windows.Forms.Cursor (separate from another library's Cursor).

Prevent mouse from leaving my form

I've attached some MouseMove and MouseClick events to my program and next up is one of these:
Get "global" mouse movement, so that I can read the mouse location even outside the form.
Prevent my mouse from leaving the form in the first place.
My project is a game so it'd be awesome to prevent the mouse leaving my form like most other games do (ofc. you can move it out if you switch focus with alt+tab fe.) and taking a look at answers to other questions asking for global mosue movement, they seem pretty messy for my needs.
Is there an easy way to prevent my mouse from going outside my form's borders? Or actually to prevent it from going OVER the borders in the first place, I want the mouse to stay inside the client area.
Additional info about the game:
The game is a short, 5-30 seconds long survival game (it gets too hard after 30 seconds for you to stay alive) where you have to dodge bullets with your mouse. It's really annoying when you move your mouse out of the form and then the player (System.Windows.Forms.Panel attached to mouse) stops moving and instantly gets hit by a bullet. This is why preventing mouse from leaving the area would be good.
Late answer but might come in handy. You could subscribe the form to MouseLeave and MouseMove events and handle them like this :
private int X = 0;
private int Y = 0;
private void Form1_MouseLeave(object sender, EventArgs e)
{
Cursor.Position = new Point(X, Y);
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (Cursor.Position.X < this.Bounds.X + 50 )
X = Cursor.Position.X + 20;
else
X = Cursor.Position.X - 20;
if (Cursor.Position.Y < this.Bounds.Y + 50)
Y = Cursor.Position.Y + 20;
else
Y = Cursor.Position.Y - 20;
}
The above will make sure the mouse cursor never leaves the bounds of the form. Make sure you unsubscribe the events when the game is finished.
Edit :
Hans Passants's answer makes more sense than my answer. Use Cursor.Clip on MouseEnter :
private void Form1_MouseEnter(object sender, EventArgs e)
{
Cursor.Clip = this.Bounds;
}
You could free the cursor in case of any error/crash (I'm sure you could catch'em) :
Cursor.Clip = Rectangle.Empty;
You cannot trap the mouse, that would prevent the user from, say, operating the Start menu. Closest you can get is assigning the Cursor.Clip property. But it is easily defeated by the user pressing Ctrl+Esc for example, there is no notification for this.
Best thing to do is to subscribe the form's Deactivated event, it reliably tells you that the user switched to another program. The Activated event tells you when the user moved back. Of course the user will have few reasons to actually do this when the game score depends on keeping a game object moving. So don't forget to give the user an easy way to pause the game with, say, the Escape key.
I don't know a solution for your exact problem, but I have a completely different idea for you. I don't know how your game works, but based on what you told me, why not make it a step harder: Add borders to the game-area, for example 4 pixels wide rectangles, which you are not allowed to touch. If you touch them, you die and the mouse gets released.
You can use the Cursor class. For example:
int X = Cursor.Position.X;
int Y = Cursor.Position.Y;
As for preventing the user to move the mouse outside the form, the best approach would probably be if you had someway to know what is the coordinates of your form on the screen and attach a MouseMove event, and check if the mouse is inside the form rectangle.
To know the form position on the screen take a look at this question.
I wouldn't recommend the global mouse movement control for two reasons.
It's bad design, you should respect the bounds of the operating system. Make the application full screen if you want this kind of behaviour. The only applications that should perform these kind of operations are "kiosk" mode applications which lock down the entire OS (to prevent operator abuse).
Global key hooks are messy, aren't guaranteed to work and are dangerous because they affect a key part of the operating system (all controls). A bug in your code could result in requiring a reboot on the machine.
That said, last time I checked (a while ago, on Vista) SetWindowsHookEx still works (but its not officially supported IIRC), it's an unmanaged call so you'll have to pinvoke but with it you can refuse to pass on messages that would move the mouse outside of the bounds of your application. I'm not 100% sure if the OS will let you beat it to the cursor control (I've only blocked keyboards before on desktop boxes) but its probably your best shot.

Capture mouse movement and export to image [code | app]

To get more in depth information about the usage of WinForm or Webapplications I want to capture mouse-movement and click information. It would be perfect if this could be rendered to an image.
The result would be something like this:
The question is how does one start with creating an app like this?
How do I receive mousemovements and clicks when its a process from another application?
How convert mousemovements to an image?
(Anyone know if there is a opensource of free/cheap app which can do this)
IOGraphica is able to do this, but it is in Java and it is free, but not open source.
I would try to capture any mouse movement/click of your windows and store it in a collection. When you finished recording - try to draw your image. I would recommend looking for "c# capture mouse" or "mouse hook" in google. Some time ago I did this for getting a keyboard hook. You may have a look at Processing Global Mouse Events.
In terms of code this may help:
Dictionary<Point, MouseEventInfo> dict = new Dictionary<Point, MouseEventInfo>();
/// see given link to find the correct way to get this kind of event
public void mouse_event(....)
{
/// get mouse coordinates
/// create point struct
/// check if point exists in DICT
/// no - add new MouseEventInfo at Point
/// yes - access MouseEventInfo object and increase a value according to the event
}
public void onFinished()
{
/// create new bitmap/image - width/height according to your screen resultion
/// iterate through all MouseEventInfo objects and draw any information
}
/// stores mouse event info for a point
class MouseEventInfo
{
Point p;
int moved=0;
int clicked=0;
int doubleClicked=0;
}
I know this is just a piece of pseudoCode - anyway - I hope this may help you! Ah - keep in mind that any kind of hook (keyboard, mouse or anything else) may result in a virus alert of your antiVir.
hth
If you're looking for something which you could run externally and track mouse movement and clicks, you might find this mouse/keyboard hooking project over at codeproject.com useful:
http://www.codeproject.com/KB/system/globalmousekeyboardlib.aspx
There's a sample application and a hooking lib with full source. It'd be a starting point to use in your efforts.

Creating HotSpots in C#

... Is it possible to create hot-spots in C# so that when the mouse is over a certain area an event gets triggered?
Your standard From object exposes a OnMouseMove event. Given that you don't have any controls where the hot spots will be, you could just handle the coordinates in that event:
protected override void OnMouseMove(MouseEventArgs mouseEvent)
{
string X = mouseEvent.X.ToString();
string Y = mouseEvent.Y.ToString();
//Add code here to match X & Y to your hot spot coordinates.
}
Create a transparent Panel (truly transparent - by setting the WS_EX_TRANSPARENT bit in its extended window style - here's how), put it in the position you want on top of other controls, and handle MouseMove on it.
Add a MouseHover event handler for the control(s) that you want your hotspot over.
You can use WndProc to capture windows messages, or you could use GetCursorPos to get the cursor position on the screen.

Categories

Resources