Onscreen cursor positioning with user's input [duplicate] - c#

I want to simulate mouse movement every x seconds. For that, I'll use a timer (x seconds) and when the timer ticks I'll make the mouse movement.
But, how can I make the mouse cursor move using C#?

Take a look at the Cursor.Position Property. It should get you started.
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}

First Add a Class called Win32.cs
public class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
public POINT(int X, int Y)
{
x = X;
y = Y;
}
}
}
You can use it then like this:
Win32.POINT p = new Win32.POINT(xPos, yPos);
Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

Related

Is it possible to move cursor anywhere in the screen using c#? [duplicate]

I want to simulate mouse movement every x seconds. For that, I'll use a timer (x seconds) and when the timer ticks I'll make the mouse movement.
But, how can I make the mouse cursor move using C#?
Take a look at the Cursor.Position Property. It should get you started.
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
First Add a Class called Win32.cs
public class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
public POINT(int X, int Y)
{
x = X;
y = Y;
}
}
}
You can use it then like this:
Win32.POINT p = new Win32.POINT(xPos, yPos);
Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

How i can set starting point of Coordinate system in top left corner of Form? [duplicate]

This question already has answers here:
Cursor Position relative to Application
(3 answers)
Closed 6 years ago.
How i can set starting point of coordinate system in top left corner of Form ? Because it set starting point on top left corner of monitor not form but I need starting point in top left corner of Form..
Here is code what i'm try to do:
int x, y;
string _x, _y;
private void GetCursor()
{
_x = MousePosition.X.ToString();
x = int.Parse(_x);
label2.Text = _x;
_y = MousePosition.Y.ToString();
y = int.Parse(_y);
label4.Text = _y;
}
private void MoveButton()
{
button1.Location = new Point(x,y);
}
private void timer1_Tick(object sender, EventArgs e)
{
GetCursor();
MoveButton();
}
Thanks.
First Add Class (Win32.cs)
public class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
}
}
Then Call it From event :
Win32.POINT p = new Win32.POINT();
p.x = Convert.ToInt16(txtMouseX.Text);
p.y = Convert.ToInt16(txtMouseY.Text);
Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);
With txtMouseX and txtMouseY is custom parameter. I think this should at (0, 0).
You can use the Control.PointToClient method
Point localPoint = myForm.PointToClient(Cursor.Position);
label2.Text = localPoint.X.ToString();
label4.Text = localPoint.Y.ToString();

Selecting a Screenshot isn't accurate in C# and WPF

i made a program for taking a schreenshot from a selected area on the screen but it isn't accurate and i can't figure out why. It's problably because of mouse coordinates but I don't know what I did wrong. Maybe some of you could figure it out. The screenshot is always off and it catches the area of the screen above the actual selection and therefore "cuts" the lower part of the selection . This is my code:
public partial class Selektiranje : Window
{
public double x;
public double y;
public double width;
public double height;
public bool isMouseDown = false;
public Selektiranje()
{
InitializeComponent();
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
isMouseDown = true;
x = e.GetPosition(null).X; //Selekcija Screenshota
y = e.GetPosition(null).Y;
}
public void Window_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (this.isMouseDown)
{
double curx = e.GetPosition(null).X;
double cury = e.GetPosition(null).Y;
System.Windows.Shapes.Rectangle r = new , System.Windows.Shapes.Rectangle();
SolidColorBrush brush = new SolidColorBrush(Colors.White);
r.Stroke = brush;
r.Fill = brush;
r.StrokeThickness = 1;
r.Width = Math.Abs(curx - x);
r.Height = Math.Abs(cury - y);
selekt.Children.Clear();
selekt.Children.Add(r);
Canvas.SetLeft(r, x);
Canvas.SetTop(r, y);
if (e.LeftButton == MouseButtonState.Released)
{
selekt.Children.Clear();
width = e.GetPosition(null).X - x;
height = e.GetPosition(null).Y - y;
this.CaptureScreen(x, y, width, height);
this.x = this.y = 0;
this.isMouseDown = false;
this.Close();
}
}
}
public void CaptureScreen(double x, double y, double width, double height)
{
int ix, iy, iw, ih;
ix = Convert.ToInt32(x);
iy = Convert.ToInt32(y);
iw = Convert.ToInt32(width);
ih = Convert.ToInt32(height);
Bitmap slika = new Bitmap(iw, ih, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(slika);
g.CopyFromScreen(ix, iy, 0, 0,new System.Drawing.Size(iw, ih),CopyPixelOperation.SourceCopy);
public void SaveScreen(double x, double y, double width, double height)
{
int ix, iy, iw, ih;
ix = Convert.ToInt32(x);
iy = Convert.ToInt32(y);
iw = Convert.ToInt32(width);
ih = Convert.ToInt32(height);
try
{
Bitmap slika = new Bitmap(iw, ih);
Graphics gr1 = Graphics.FromImage(slika);
IntPtr dc1 = gr1.GetHdc();
IntPtr dc2 = NativeMethods.GetWindowDC(NativeMethods.GetForegroundWindow());
NativeMethods.BitBlt(dc1, ix, iy, iw, ih, dc2, ix, iy, 13369376);
gr1.ReleaseHdc(dc1);
System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
dlg.DefaultExt = "png";
dlg.Filter = "Png Files|*.png";
DialogResult res = dlg.ShowDialog();
if (res == System.Windows.Forms.DialogResult.OK)
slika.Save(dlg.FileName, ImageFormat.Png);
}
catch
{
}
}
internal class NativeMethods
{
[DllImport("user32.dll")]
public extern static IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hwnd);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();
[DllImport("gdi32.dll")]
public static extern UInt64 BitBlt(IntPtr hDestDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, System.Int32 dwRop);
}
}
}
You need Cursor.Position (MSDN) in Window_MouseDown() and Window_MouseMove() which returns absolute mouse coordinates.
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
isMouseDown = true;
x = Cursor.Position.X;
y = Cursor.Position.Y;
}
Code of a fully working solution (for me) below. I removed unnecessary code such as drawing the rectangle. In addition, I hide the form before taking the screenshot. You could also set the form's background color to a specific value and set the transparency key to the same value or something.
But the basic concept remains: use absolute screen coordinates.
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media;
using PixelFormat = System.Drawing.Imaging.PixelFormat;
using Rectangle = System.Windows.Shapes.Rectangle;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public double x;
public double y;
public double width;
public double height;
public bool isMouseDown;
public Form1()
{
InitializeComponent();
}
public void SaveScreen(double x, double y, double width, double height)
{
var ix = Convert.ToInt32(x);
var iy = Convert.ToInt32(y);
var iw = Convert.ToInt32(width);
var ih = Convert.ToInt32(height);
try
{
var slika = new Bitmap(iw, ih, PixelFormat.Format32bppArgb);
var g = Graphics.FromImage(slika);
g.CopyFromScreen(ix, iy, 0, 0, new Size(iw, ih), CopyPixelOperation.SourceCopy);
var dlg = new SaveFileDialog
{
DefaultExt = "png",
Filter = "Png Files|*.png"
};
var res = dlg.ShowDialog();
if (res == DialogResult.OK) slika.Save(dlg.FileName, ImageFormat.Png);
}
catch
{
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
isMouseDown = true;
x = Cursor.Position.X;
y = Cursor.Position.Y;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
width = Cursor.Position.X - x;
height = Cursor.Position.Y - y;
Hide();
Size = new Size(0, 0);
Application.DoEvents();
SaveScreen(x, y, width, height);
x = y = 0;
isMouseDown = false;
Close();
}
}
}
Graphics.CopyFromScreen needs the screen coordinates to take picture. You are passing coorduinates relative to form because of using e.x and e.y of MouseEventArgs. You should use screen coordinates of mouse instead, using Cursor.Position or MousePosition that are identical.
If you are using WPF
There are many options that may help you to get screen coordinates, some of those options:
Option 1
You can use PointToScreen method to convert the coordinates to screen coordinates.
Option 2
In WPF you cant use those methods, the most simple way would be add a reference to System.Windows.Forms.dll to your WPF project and then use System.Windows.Forms.Control.MousePosition which is static.
Option 3
As another option you can add a reference to System.Drawing.dll and use this:
[System.Runtime.InteropServices.DllImport("user32.dll")]
[return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref PointStruct point);
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
internal struct PointStruct
{
public Int32 X;
public Int32 Y;
};
public static System.Drawing.Point MousePosition()
{
var mousePosition = new PointStruct();
GetCursorPos(ref mousePosition);
return new System.Drawing.Point(mousePosition.X, mousePosition.Y);
}
Then you can use MousePosition() to get the current position of mouse on screen.

Save and Export Mouse co-ordinates Visual Studio C#

I am trying to create an application using which i will be able to click and drag the mouse any where inside a frame and the corresponding mouse coordinates should be saved in to a stack or a list and i should be able to export the list onto a database or excel file.
At present i am able to retrieve the mouse coordinates using,
base.OnMouseMove(e);
x = e.X;
y = e.Y;
toolStripStatusLabelXY.Text = x.ToString();
toolStripStatusLabel1.Text = y.ToString();
Is it possible to do this in a C# win32 form application.
Thankyou
Add this reference to code
using System.Runtime.InteropServices;
and add this code to your code
[DllImport("user32.dll", CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons,uint dwExtraInfo);
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
public void DoLeftMouseClick(int x int y)
{
//this function perfoms left click a position you want
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, x, y, 0, 0);
}
public void DoLeftMouseClick(int x int y)
{
//this function perfoms right click a position you want
mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, x, y, 0, 0);
}
If you want to drag use theese;
public void DoLeftMouseClickDown(int x int y)
{
mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
}
public void DoLeftMouseClickUp(int x int y)
{
mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
}
public void DoLeftMouseClickDown(int x int y)
{
mouse_event(MOUSEEVENTF_RIGHTDOWN , x, y, 0, 0);
}
public void DoLeftMouseClickUp(int x int y)
{
mouse_event(MOUSEEVENTF_RIGHTUP, x, y, 0, 0);
}
Use theese like this;
DoLeftMouseClickDown(positionToClick.X,positionToClick.Y);
DoLeftMouseClickUp(positionToDrag.X,positionToDrag.Y)
this drags the item which is at positionToClick to positionToDrag

How to move mouse cursor using C#?

I want to simulate mouse movement every x seconds. For that, I'll use a timer (x seconds) and when the timer ticks I'll make the mouse movement.
But, how can I make the mouse cursor move using C#?
Take a look at the Cursor.Position Property. It should get you started.
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
First Add a Class called Win32.cs
public class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
public POINT(int X, int Y)
{
x = X;
y = Y;
}
}
}
You can use it then like this:
Win32.POINT p = new Win32.POINT(xPos, yPos);
Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

Categories