Desktop screenshot in WPF

前端 未结 1 413
死守一世寂寞
死守一世寂寞 2020-12-15 14:32

How can I take a screenshot of the desktop in WPF? Preferably with the mouse cursor showing.

1条回答
  •  天命终不由人
    2020-12-15 15:07

    Without trying to steal the answer, use the code give in the CodeProject article referenced by Johannes to create the GDI bitmap. You can then use the following code to convert it into a BitmapSource for use in WPF:

        public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
        {
            var hBitmap = source.GetHbitmap();
    
            try
            {
                return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    hBitmap,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
            }
            catch (Win32Exception)
            {
                return null;
            }
            finally
            {
                NativeMethods.DeleteObject(hBitmap);
            }
        }
    

    where the code for NativeMethods.DeleteObject() is:

        [DllImport("gdi32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool DeleteObject(IntPtr hObject);
    

    0 讨论(0)
提交回复
热议问题