如何在c#中获取自定义图像光标的坐标?

时间:2011-09-07 05:34:15

标签: c# .net image graphics drawing

 Bitmap hh = (Bitmap)System.Drawing.Bitmap.FromFile("example.png");
 Graphics.FromImage(hh);
 IntPtr ptr = hh.GetHicon();
 Cursor c = new Cursor(ptr);
 this.Cursor = c;

我使用此代码创建自定义图像光标。我希望在Click事件时检索此自定义图像光标的坐标。因此,当单击图片框中加载的图像时,可以使用这些坐标在图片框中绘制此光标的图像。我在C#中这样做。

我尝试了另一种方法

public partial class Form1 : Form
{
    private Bitmap _bmp = new Bitmap(250, 250);

    public Form1()
    {
        InitializeComponent();

        panel1.MouseDown += new MouseEventHandler(panel1_MouseDown);
        panel1.Paint += new PaintEventHandler(panel1_Paint);

        using (Graphics g = Graphics.FromImage(_bmp))
            g.Clear(SystemColors.Window);
    }

    private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        Point mouseDownLocation = new Point(e.X, e.Y);
        label1.Text = mouseDownLocation.X.ToString();
    }

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawImage(_bmp, new Point(0, 0));
    }

    private void panel1_MouseDown(object sender, MouseEventArgs e)
    {
        using (Graphics g = Graphics.FromImage(_bmp))
        {
            g.DrawString("Mouse Clicked Here!", panel1.Font, Brushes.Black, e.Location);
        }
        panel1.Invalidate();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        panel1.Image.Save(@"C:\test.jpg", ImageFormat.Jpeg);
    }

但是当我尝试这样保存图像时,我得到一个异常:对象引用未设置为对象的实例

请注意,上面代码中的panel1是指图片框

2 个答案:

答案 0 :(得分:2)

要在PictureBox上获取鼠标的坐标,您不应该处理OnClick事件,而是OnMouseDown,例如以这种方式:

private void pb_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) 
{
  Point mouseDownLocation = new Point(e.X, e.Y);
}

现在您拥有mouseDownLocation,其中包含您要查找的坐标。

答案 1 :(得分:1)

我知道获取鼠标坐标的方法,你可以像

一样编码

Cursor.Position.X和Cursor.Position.Y获取鼠标下的坐标