如何让图片框跟随光标 c# windows 形式
How to have a picture box follow cursor c# windows forms
我正在制作一个射击游戏,您可以在其中单击目标来得分,我想知道我怎么才能拥有它,所以我有一个图片框而不是光标来充当瞄准标线。
或许您可以通过订阅表单的事件MouseMove
来实现这个需求。然后通过代码获取鼠标位置,重新设置PictureBox的位置。
这里有一个演示,你可以参考。
public Form1()
{
InitializeComponent();
}
[DllImport("user32.dll", EntryPoint = "ShowCursor", CharSet = CharSet.Auto)]
public extern static void ShowCursor(int status);
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
Point p1 = MousePosition;
// Get the mouse position in the form
Point p2 = PointToClient(p1);
// Reset picturebox location
pictureBox1.Location = new Point(p2.X - pictureBox1.Width /2 , p2.Y - pictureBox1.Height /2);
}
private void Form1_Load(object sender, EventArgs e)
{
// Load picture
pictureBox1.Image = Image.FromFile(@"D:\pic123\target.png");
// Hide cursor
ShowCursor(0);
}
我正在制作一个射击游戏,您可以在其中单击目标来得分,我想知道我怎么才能拥有它,所以我有一个图片框而不是光标来充当瞄准标线。
或许您可以通过订阅表单的事件MouseMove
来实现这个需求。然后通过代码获取鼠标位置,重新设置PictureBox的位置。
这里有一个演示,你可以参考。
public Form1()
{
InitializeComponent();
}
[DllImport("user32.dll", EntryPoint = "ShowCursor", CharSet = CharSet.Auto)]
public extern static void ShowCursor(int status);
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
Point p1 = MousePosition;
// Get the mouse position in the form
Point p2 = PointToClient(p1);
// Reset picturebox location
pictureBox1.Location = new Point(p2.X - pictureBox1.Width /2 , p2.Y - pictureBox1.Height /2);
}
private void Form1_Load(object sender, EventArgs e)
{
// Load picture
pictureBox1.Image = Image.FromFile(@"D:\pic123\target.png");
// Hide cursor
ShowCursor(0);
}