get cursor position - c#

I have an usercontrol called TaskControl and a button for creating other usercontrols by dragging. I want the new user control that appears to be at the same coordinates where my cursor is. Below it is my code. It doesn't want to appear at those coordinates and the new usercontrol appears behind the old one.
My code:
private void button1_Click(object sender, EventArgs e)
{
Point localCoordinates = this.PointToClient(Cursor.Position);
TaskControl t = new TaskControl();
t.Location = new Point(Cursor.Position.X,Cursor.Position.Y);
t.MouseDown += new MouseEventHandler(t_MouseDown);
t.MouseMove += new MouseEventHandler(t_MouseMove);
t.MouseUp += new MouseEventHandler(t_MouseUp);
this.Controls.Add(t);
}

You have to work out that using Control.MousePosition static property, which
Gets the position of the mouse cursor in screen coordinates.
After move your use control to the coordinates retrived. Please note, that depends on how you architect your UI, you may need to convert coordinates to client. For this can use
Control.PointToClient static method, which:
Computes the location of the specified screen point into client
coordinates.

Take a look Control.MousePosition
Gets the position of the mouse cursor in screen coordinates.

Related

Re-position WPF window after resizing to mouse location

I am creating a small game that resizes the main window to fit a growing board. I want to re-position the window to keep the button that was clicked under the mouse after resizing. Currently, when clicked the board gets wider and moves the button away from the mouse.
How do I define the button as the anchor point when I move the window?
I don't know if there is a way to use the button as an anchor point. But after a little thinking, i came up with a code that can work for you.
Basically, i'm using the mouse relative to the button position before and after the resize to move the window accordingly. I hope it helps.
private void Btn1Click(object sender, RoutedEventArgs e)
{
int widthGrowth = 50;
int heightGrowth = 80;
Button btn = sender as Button;
Point oldMousePosition = Mouse.GetPosition(btn);
Width += widthGrowth;
Height += heightGrowth;
Point newMousePosition = Mouse.GetPosition(btn);
Left += newMousePosition.X - oldMousePosition.X;
Top += newMousePosition.Y - oldMousePosition.Y;
}

Visual Studio C# how to move a button's X position by mouse without flicker

So I'm trying to make a slider. I'm using my cursor to move a button's x position.
I have 3 functions, the mouseDown, mouseUp and the mouseMove function. In the mouseUp and mouseDown functions I set a variable to true and false to tell the program that the mouse is clicked or not. In the mouseMove function I tell the program to set the button's x position to the x position of the mouse when the mouse is clicked. This works but has 2 problems.
The first problem is that when I press the button and move it, the button moves along with the mouse's x but it has a space between the mouse and the button. It looks a bit like this:
CURSOR.......BUTTON
The space between the cursor and button change when I change the resolution of the form.
The second problem is that when I move the button it flickers a bit. It only does this at higher speeds but it is a problem in my case.
My code looks like this:
bool mouseDown = false;
private void volumeGrabBT_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseDown = true;
}
}
private void volumeGrabBT_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mouseDown = false;
}
}
private void volumeGrabBT_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown == true)
{
Point volumeBTPoint = new Point();
volumeBTPoint.X = Cursor.Position.X;
volumeBTPoint.Y = volumeGrabBT.Location.Y;
volumeGrabBT.Location = volumeBTPoint;
}
}
The volumeGrabBT is the button I'm trying to move along with the mouse.
The volumeBTPoint is the point of the button I'm trying to set the button's position to.
I hope someone can help me fix these problems. Thanks in advance!
I believe that flickering can be fixed by setting some additional form styles: SetStyle(ControlStyles.AllPaintingInWmPaint |ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
in form's constructor. It will use double buffering and generally just draws faster.
For the Cursor class, it's relative to the screen, not your form. You can use this.PointToClient() function to get client's space position of cursor, like this:
Point clientCursor = this.PointToClient(Cursor.Position);
and then use clientCursor to get exact X in your client space.
You have to translate screen coordinates to client coordinates.
Point volumeBTPoint = new Point();
Point point = this.PointToClient(Cursor.Position);
volumeBTPoint.X = point.X;
volumeBTPoint.Y = volumeGrabBT.Location.Y;
volumeGrabBT.Location = volumeBTPoint;
Instead of this you should use button's parent control (Panel, GroupBox, etc).

GMap - cannot detect clicking on polygon

IsMouseOverMarker property detects clicking on marker just fine, but when trying to use IsMouseOverPolygon property of GMap Control to detect if user clicked on polygon line - it doesn't seem to be working.
Note: PolygonEnabled property of GMap control is set to True.
The OnPolygonClick event doesn't even fire:
private void gMap_OnPolygonClick(GMapPolygon item, MouseEventArgs e) {
double pLat = item.From.Value.Lat;
}
Map Click event does fire, but the 'IsMouseOverPolygon` never gets True value:
private void gMap_Click(object sender, EventArgs e) {
if (gMap.IsMouseOverMarker) {
MessageBox.Show("Clicked on marker and it works!");
}
if (gMap.IsMouseOverPolygon) {
MessageBox.Show("clicked on line - never works");
}
}
I wonder if there is something wrong in a way I'm adding polygons or is it because in my case it's just lines:
GMapOverlay polyOverlay = new GMapOverlay("polygons");
gMap.Overlays.Add(polyOverlay);
List<PointLatLng> points = new List<PointLatLng>();
points.Add(start);
points.Add(end);
polygon = new GMapPolygon(points, "mypolygon");
polygon.Stroke = new Pen(Color.Blue, 5);
polyOverlay.Polygons.Add(polygon);
So, the question is: how should I go about detecting mouse click on those lines?
I can see two issues within the code. First you need to explicitely define the polygon as HitTestVisible:
polygon.IsHitTestVisible = true;
Second, to set up a polygon add at least three points that are not aligned and actually spawn an area. I've found that the click will only be noticed on an actual area, where in theory a polygon can consist of two points.
With the hints above the check for gMap.IsMouseOverPolygon should return true then.

How to get the correct position of an Image in WPF?

I am a beginner in Windows Presentation Foundation.
I have a Canvas in which there is a small square canvas. Inside this small square canvas i have an image.
I have attached an event handler to this image , When user click on this image user can get the current position of the image.
Whenever user click on that image , he/she will get a prompt message box in which user get the current image position to print.
Everything is working fine when user press Left click on the image .
But, the problem arises when user first pressing the right click on the image and suddenly pressing Left click on the same image , It is not showing the same value.
I have not attached any event handler on the right click.
I am using the following code :
Image objImage = new Image();
objImage .Height =12;
objImage .Width = 12;
objImage .Stretch = Stretch.UniformToFill;
imageAck.MouseLeftButtonDown += new MouseButtonEventHandler(objImageMouseLeftButtonDown);
private void objImageMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Point mouseCurrent = e.GetPosition(null);
}
I am notgetting the same value in mouseCurrent
Using e.GetPosition, this gets the position of the mouse pointer relative to the element that was clicked, not the canvas that the element belongs to.
To get the actual position of the image on the Canvas, you need to use the Canvas.GetLeft, and Canvas.GetTop methods. Here is an example:
private void objImageMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
double left = Canvas.GetLeft((UIElement)sender);
double top = Canvas.GetTop((UIElement)sender);
}
You can then use the left and top variables for whatever purpose you need.
Finally, I got an answer by Googling some hour .....
Point currentMousePosition = Mouse.GetPosition(Application.Current.MainWindow);

Getting a line that has the coordinates defined by the mouse location

I'm trying to make a little graphics program that has a circle of diameter 100 on the screen and from the center of it, a line is coming out of it that is always attached to the mouse pointer until such time that the user does a click, and then the line is permanently drawn. It's exactly like MSPaint's line, except that starting point is always the center of the circle.
I tried a few things that DON'T work.
I can get the line to appear only after a mouse-click. That's not what I want. I want the line to always be present and pivoting from the circle-center until the mouse is clicked and then it's then permanently on the screen.
I can get a smeary thing where the line is always being drawn. It makes a sort of star shape, but that's not what I want either.
Basically, I want the same functionality that you have in MSPaint when you draw a line. What am I supposed to do? Draw the line and then erase it a second later, and then draw it again when the mouse is in a new position? I tried something like that, but it does a thing where it erases the background a little bit, and then the line is only drawn when the mouse is in motion, but not when the mouse is stationary.
If anyone can provide a code snippet, that'd be great. Or just some pseudo-code.
Is this the right pseudo code?
Start:
Left click and a line appears from center of circle to mouse tip
Line stays there until a new mouse coordinate is made (how do I keep track)?
Line from center of circle to original location gets erased
New line is made to new location of mouse coordinates.
I think this something of a state-machine to use what I learned in digital class. How are states implemented in C#?
Any help would be appreciated, and thanks to everyone that can understand my question even though I'm probably not using the proper terminology.
So short answer is you will need some custom painting. The longer answer involves custom drawing, and event handling.
The other piece of code you need is a list of some sort to hold all of the lines. The code below creates a user control and does the custom painting without relying on a state machine. To test it, create a new project add a user control called UserControl1, and add it to a form. Make sure you tie into the listed events.
I tried to comment the relevant sections and this shows a quick and dirty way to do what you appear to be trying to do.
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace CustomDrawingAndEvents
{
public partial class UserControl1 : UserControl
{
private struct MyLine
{
public Point mStart;
public Point mEnd;
public MyLine(Point xStart, Point xEnd)
{
mStart = xStart;
mEnd = xEnd;
}
}
private List<MyLine> mLines;
private Point mCircleCenter;
private Point mMousePosition;
public UserControl1()
{
InitializeComponent();
mLines = new List<MyLine>();
//Double Buffer to prevent flicker
DoubleBuffered = true;
//Create the center for our circle. For this just put it in the center of
//the control.
mCircleCenter = new Point(this.Width / 2, this.Height / 2);
}
private void UserControl1_MouseClick(object sender, MouseEventArgs e)
{
//User clicked create a new line to add to the list.
mLines.Add(new MyLine(mCircleCenter, e.Location));
}
private void UserControl1_MouseMove(object sender, MouseEventArgs e)
{
//Update mouse position
mMousePosition = e.Location;
//Make the control redraw itself
Invalidate();
}
private void UserControl1_Paint(object sender, PaintEventArgs e)
{
//Create the rect with 100 width/height (subtract half the diameter to center the rect over the circle)
Rectangle lCenterRect = new Rectangle(mCircleCenter.X - 50, mCircleCenter.Y - 50, 100, 100);
//Draw our circle in the center of the control with a diameter of 100
e.Graphics.DrawEllipse(new Pen(Brushes.Black), lCenterRect);
//Draw all of our saved lines
foreach (MyLine lLine in mLines)
e.Graphics.DrawLine(new Pen(Brushes.Red), lLine.mStart, lLine.mEnd);
//Draw our active line from the center of the circle to
//our mouse location
e.Graphics.DrawLine(new Pen(Brushes.Blue), mCircleCenter, mMousePosition);
}
}
}

Categories

Resources