【Csharp】获取实时的鼠标光标位置,测试用——做窗口软件绘图需要确定光标位置
前言
我的爱沉重,污浊,里面带有许多令人不快的东西,比如悲伤,忧愁,自怜,绝望,我的心又这样脆弱不堪,自己总被这些负面情绪打败,好像在一个沼泽里越挣扎越下沉。——《挪威的森林》
\;\\\;\\\;
目录
- 前言
- Cursor
Cursor
把窗口放在左下角,这样在运行测试别的窗口程序的时候,就可以实时显示位置了。
using static System.Net.Mime.MediaTypeNames;
namespace CursorPoint
{
public partial class Form1 : Form
{
private System.Windows.Forms.Timer timer; // 声明 Timer 控件
public Form1()
{
InitializeComponent();
//居中
//this.CenterToScreen();
// 获取主屏幕的实际尺寸
Rectangle b = Screen.PrimaryScreen.Bounds;
// 计算窗体应该放置的位置
int x = 0; // 屏幕的左边缘
int y = b.Height - this.Height; // 屏幕高度减去窗体高度
// 设置窗体位置
this.Location = new Point(x, y);
// 输出计算结果
Console.WriteLine($"Screen bounds: ({b.Width}, {b.Height})");
Console.WriteLine($"Form size: ({this.Width}, {this.Height})");
Console.WriteLine($"New form location: ({x}, {y})");
/*
窗口计算都是对的,但是Location设置位置一直不对!窗口还跳动
要把StartPosition,改成Manual!!!这样就没问题了!
*/
//置顶
this.TopMost = true;
//定时器设置
timer = new System.Windows.Forms.Timer();
timer.Interval = 100; //ms
timer.Tick += new EventHandler(Timer_Tick);
timer.Start(); // 开始计时
}
//这个只有鼠标到窗口上才起作用
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
UpdateCursorPoint();
}
//实时显示鼠标位置,核心函数
private void UpdateCursorPoint()
{
// 获取全局的鼠标位置并更新 Label
Point globalCursorPosition = Cursor.Position;
string text = $"({globalCursorPosition.X}, {globalCursorPosition.Y})";
// 更新 Label 的文本
label1.Text = text;
}
private void Timer_Tick(object sender, EventArgs e)
{
UpdateCursorPoint();
}
}
}
\;\\\;\\\;