2011-09-07 63 views
1
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#中這樣做。如何獲得自定義圖像光標在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代碼是指圖片框

+0

下的座標的方式是拋出的異常,當你點擊按鈕?如果是這樣,你應該檢查'panel1'是否爲'null'或面板的'Image'屬性。 – WaltiD

+0

是的,我收到錯誤,當我點擊按鈕來執行保存命令 – rainbower

+0

你有空的Panel1.image,因爲你在繪畫方法中繪製它,而不是永久分配給圖像屬性。 –

回答

2

爲了讓你不應該處理OnClick事件,但onmousedown事件一個PictureBox鼠標的座標,例如以這種方式:

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

現在你有mouseDownLocation其中包含你正在尋找的座標。

+0

感謝您的守則。 – rainbower

+0

它不工作 – rainbower

+1

請顯示您的代碼並解釋不起作用。編輯你的問題,讓我們有更好的代碼格式比評論。 –

1

我知道得到鼠標的座標,你可以像

Cursor.Position.X和Cursor.Position.Y編寫代碼的時候獲得鼠標