2013-08-21 105 views
0

我有一個.cur文件路徑("%SystemRoot%\cursors\aero_arrow.cur")我想在圖像控件中顯示。所以我需要將Cursor轉換爲ImageSource。我嘗試了CursorConverter和ImageSourceConverter,但沒有運氣。我也嘗試從光標創建圖形,然後將其轉換爲位圖,但這也不起作用。然後我發現在這個線程中接受的答案:http://social.msdn.microsoft.com/Forums/vstudio/en-US/87ee395c-9134-4196-bcd8-3d8e8791ff27/is-there-any-way-convert-cursor-to-icon如何將光標轉換爲ImageSource

現在有趣的是,我不能創建一個新的System.Windows.Form.Cursor實例既沒有文件路徑也沒有流,因爲它會引發以下例外:

System.Runtime.InteropServices.COMException(0x800A01E1):在System.Windows 0x800A01E1(CTL_E_INVALIDPICTURE)在 System.Windows.Forms.UnsafeNativeMethods.IPersistStream.Load(的IStream PSTM):從HRESULT異常 .Forms.Cursor.LoadPicture(IStream stream)

那麼有誰能告訴我將System.Windows.Input.Cursor轉換爲ImageSource的最佳方法嗎?

那麼.ani遊標呢?如果我沒有記錯System.Windows.Input.Cursor不支持動畫遊標,那麼我怎麼能把它們展示給用戶?將它們轉換爲GIF,然後使用3D派對gif庫?

回答

2

我發現在這個線程解決方案:How to Render a Transparent Cursor to Bitmap preserving alpha channel?

所以這裏是代碼:

[StructLayout(LayoutKind.Sequential)]  
private struct ICONINFO 
{ 
    public bool fIcon; 
    public int xHotspot; 
    public int yHotspot; 
    public IntPtr hbmMask; 
    public IntPtr hbmColor; 
} 

[DllImport("user32")] 
private static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO pIconInfo); 

[DllImport("user32.dll")] 
private static extern IntPtr LoadCursorFromFile(string lpFileName); 

[DllImport("gdi32.dll", SetLastError = true)] 
private static extern bool DeleteObject(IntPtr hObject); 

private Bitmap BitmapFromCursor(Cursor cur) 
{ 
    ICONINFO ii; 
    GetIconInfo(cur.Handle, out ii); 

    Bitmap bmp = Bitmap.FromHbitmap(ii.hbmColor); 
    DeleteObject(ii.hbmColor); 
    DeleteObject(ii.hbmMask); 

    BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat); 
    Bitmap dstBitmap = new Bitmap(bmData.Width, bmData.Height, bmData.Stride, PixelFormat.Format32bppArgb, bmData.Scan0); 
    bmp.UnlockBits(bmData); 

    return new Bitmap(dstBitmap); 
} 

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) 
{ 
    //Using LoadCursorFromFile from user32.dll, get a handle to the icon 
    IntPtr hCursor = LoadCursorFromFile("C:\\Windows\\Cursors\\Windows Aero\\aero_busy.ani"); 

    //Create a Cursor object from that handle 
    Cursor cursor = new Cursor(hCursor); 

    //Convert that cursor into a bitmap 
    using (Bitmap cursorBitmap = BitmapFromCursor(cursor)) 
    { 
     //Draw that cursor bitmap directly to the form canvas 
     e.Graphics.DrawImage(cursorBitmap, 50, 50); 
    } 
} 

它爲Win形式的書面和繪製的圖像。但是可以在wpf中使用以及引用System.Windows.Forms。然後你可以將該位圖轉換爲位圖源並將其顯示在圖像控件中...

我使用System.Windows.Forms.Cursor而不是System.Windows.Input.Cursor的原因是我可以使用IntPtr句柄不能創建光標的新實例...

編輯:上述方法不適用於具有低顏色位的遊標。 另一種方法是使用Icon.ExtractAssociatedIcon代替:

System.Drawing.Icon i = System.Drawing.Icon.ExtractAssociatedIcon(@"C:\Windows\Cursors\arrow_rl.cur"); 
System.Drawing.Bitmap b = i.ToBitmap(); 

希望幫助別人......