我已經將一個文件「x.ani」導入到資源文件Resources.resx中。現在嘗試使用ResourceManager.GetObject(「aero_busy.ani」)C#:如何從資源文件加載光標?
Cursor.Current = (Cursor)ResourcesX.GetObject("aero_busy.ani");
加載該文件,但沒有奏效。(當然):)
我如何使用資源改變當前光標目的?
我已經將一個文件「x.ani」導入到資源文件Resources.resx中。現在嘗試使用ResourceManager.GetObject(「aero_busy.ani」)C#:如何從資源文件加載光標?
Cursor.Current = (Cursor)ResourcesX.GetObject("aero_busy.ani");
加載該文件,但沒有奏效。(當然):)
我如何使用資源改變當前光標目的?
我還沒有找到比轉儲到臨時文件並使用Win32加載光標從文件方法更好的方法。黑客行爲就像這樣(爲了清晰起見,我刪除了大量的樣板代碼,其中臨時文件是使用來自流的數據寫入的)。此外,所有異常處理等都被刪除。
[DllImport("User32.dll", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
private static extern IntPtr LoadCursorFromFile(String str);
public static Cursor LoadCursorFromResource(string resourceName)
{
Stream cursorStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
// Write a temp file here with the data in cursorStream
Cursor result = new Cursor(LoadCursorFromFile(tempFile));
File.Delete(tempFile);
return result.
}
您可以使用它(在加載嵌入式資源時記住名稱空間)。
Cursors.Current = LoadCursorFromResource("My.Namespace.Filename");
關於Jethro的評論和回答,我只使用了.cur(非動畫)遊標和這種方法。這種方法應該允許使用彩色遊標。 –
感謝您的寶貴迴應:)我只是想我的程序是一個便攜式的(也稱爲存根程序)我的意思是隻有一個EXE文件必須複製。但是,你的建議值得實施:)再次感謝。 –
我這樣做是通過將光標的.cur文件到項目的資源部分(我使用Visual Studio)。我不確定它是否必須是.cur,只要開發程序可以加載它。
做完,在我的代碼的變量聲明部分我創建光標文件一個MemoryStream:
private static System.IO.MemoryStream cursorMemoryStream = new System.IO.MemoryStream(myCurrentProject.Properties.Resources.myCursorFile);
...然後你可以從MemoryStream的創建光標:
private Cursor newCursor = new Cursor(cursorMemoryStream);
然後,您可以在程序中隨意指定光標,例如
pictureBox1.Cursor = newCursor;
並且新光標被編譯爲程序的一部分。
我覺得這種方式比其他人好! – moorara
但它不適用於32位深度遊標 – GorillaApe
幾圈的問題後,我找到了完美的解決方案是:
internal static Cursor GetCursor(string cursorName)
{
var buffer = Properties.Resources.ResourceManager.GetObject(cursorName) as byte[];
using (var m = new MemoryStream(buffer))
{
return new Cursor(m);
}
}
光標類不支持動畫光標。正如我在下面的回答。 – Jethro
@Jethro謝謝理解:) –