一個警告使用自定義光標與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
文件。
這是一個教程:http://www.switchonthecode.com/tutorials/csharp-tutorial-how-to-use-custom-cursors基本上它使用的PInvoke和Windows API來實現你想要什麼。 – Tigran
如果提供的文件沒有顏色,則接受的答案有效。在有顏色的情況下 - 您需要使用Windows API,如我在下面的答案中所述。 –
@ Derek W:我沒有意識到這一點。我使用的遊標確實不包含顏色信息。 –