2011-07-19 48 views
37

UserControl我想將鼠標光標從箭頭改爲手形圖標。
我目前做的是這樣的:如何在使用Windows窗體應用程序時將鼠標光標更改爲自定義的鼠標光標?

this.Cursor = Cursors.Hand; 

這是非常好的,它給了我一個鼠標光標看起來像這樣:

enter image description here

但這裏說到我的問題......這個節目一隻手指着一個手指。
我需要的是一個「抓」的手,更多的像這樣的:

enter image description here

如何做到這一點?,我如何可以加載一個圖標文件(.ICO),光標文件(。 cur)還是圖像文件(.png),並將其用作鼠標光標?

+1

這是一個教程:http://www.switchonthecode.com/tutorials/csharp-tutorial-how-to-use-custom-cursors基本上它使用的PInvoke和Windows API來實現你想要什麼。 – Tigran

+1

如果提供的文件沒有顏色,則接受的答案有效。在有顏色的情況下 - 您需要使用Windows API,如我在下面的答案中所述。 –

+0

@ Derek W:我沒有意識到這一點。我使用的遊標確實不包含顏色信息。 –

回答

17

如果你有一個光標文件:

Cursor myCursor = new Cursor("myCursor.cur"); 
myControl.Cursor = myCursor; 

否則你必須創建一個:

一些更多的信息有關custom cursors

+0

完美的作品!也感謝那個鏈接,我不知道那個網站。 –

2

你試過System.Windows.Forms.Cursor curs = new System.Windows.Forms.Cursor(file_name);

0

一個警告使用自定義光標與WinForms的Cursor類是使用流,文件名時,和資源構造函數重載提供的.cur文件必須是黑色和白色的

這意味着如果.cur文件包含除黑色和白色以外的任何顏色,這將不起作用。

Cursor myCursor = new Cursor("myCursor.cur"); 
myControl.Cursor = myCursor; 

有解決此限制的方式通過使用Windows手柄構造函數重載:

[System.Runtime.InteropServices.DllImport("user32.dll")] 
public static extern IntPtr LoadCursorFromFile(string fileName); 

然後將它傳遞給適當的Cursor構造:

通過使用Windows API創建手柄像這樣:

IntPtr handle = LoadCursorFromFile("myCursor.cur"); 
Cursor myCursor = new Cursor(handle); 
myControl.Cursor = myCursor; 

我希望這可以防止o他們抓住他們的頭被拋出ArgumentException說明:Image format is not valid. The image file may be corrupted.當使用其他Cursor構造函數重載與包含顏色的.cur文件。

0

我測試了這個方法。沒關係。這是我的申請:

[System.Runtime.InteropServices.DllImport("user32.dll")] 
    public static extern IntPtr LoadCursorFromFile(string fileName); 
    Cursor myCursor; 
    private void tsbtn_ZoomIn_Click(object sender, EventArgs e) 
    { 
     IntPtr handle = LoadCursorFromFile("view_zoom_in.cur"); 
     myCursor = new Cursor(handle); 
     zg1.Cursor = myCursor; 
    } 
相關問題