Общая ошибка в GDI+ при использовании GetHBitmap (WPF4/C#)C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Общая ошибка в GDI+ при использовании GetHBitmap (WPF4/C#)

Сообщение Anonymous »

Я использую следующий код, чтобы сделать снимок экрана и скопировать его в BitmapSource. Метод вызывается непрерывно через DispatcherTimer каждые 400 мс. Сначала я использовал этот код с .NET Framework 3.5, затем перешел на Framework 4.0. Когда программа работает некоторое время (скажем, 15 минут), она внезапно аварийно завершает работу с «Общей ошибкой в ​​GDI+» во время вызова GetHBitmap.

Когда я переключился до .NET 4.0 мне пришлось закомментировать вызов CloseHandle(), который вызвал исключение SEHException. Возможно, проблема в этом, а может и нет.

Итак, вот мой код. Надеюсь, кто-нибудь сможет помочь...

// The code is based on an example by Charles Petzold
// http://www.charlespetzold.com/pwcs/Read ... creen.html

// Import external Win32 functions

// BitBlt is used for the bit by bit block copy of the screen content
[DllImport("gdi32.dll")]
private static extern bool BitBlt(IntPtr hdcDst, int xDst, int yDst, int cx, int cy,
IntPtr hdcSrc, int xSrc, int ySrc, uint ulRop);

// DeleteObject is used to delete the bitmap handle
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);

// CreateDC is used to create a graphics handle to the screen
[DllImport("gdi32.dll")]
private static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string lpszOutput, IntPtr lpInitData);

// CloseHandle is used to close the bitmap handle, which does not work with Framework 4 :(
// [DllImport("Kernel32")]
// private static extern bool CloseHandle(IntPtr handle);

public static void getBitmap(ref BitmapSource bms)
{
// define the raster-operation code for the BitBlt method
// SRCOPY copies the source directly to the destination
const int SRCCOPY = 0x00CC0020;

// The screenshot will be stored here
Bitmap bm;

// Get a Graphics object associated with the screen
Screen s = UIHelper.getScreenHandle();
Graphics grfxScreen = Graphics.FromHdc(CreateDC(null, s.DeviceName, null,
IntPtr.Zero));

// Create a bitmap the size of the screen.
bm = new Bitmap((int)grfxScreen.VisibleClipBounds.Width,
(int)grfxScreen.VisibleClipBounds.Height, grfxScreen);

// Create a Graphics object associated with the bitmap
Graphics grfxBitmap = Graphics.FromImage(bm);

// Get handles associated with the Graphics objects
IntPtr hdcScreen = grfxScreen.GetHdc();
IntPtr hdcBitmap = grfxBitmap.GetHdc();

// Do the bitblt from the screen to the bitmap
BitBlt(hdcBitmap, 0, 0, bm.Width, bm.Height,
hdcScreen, 0, 0, SRCCOPY);

// Release the device contexts.
grfxBitmap.ReleaseHdc(hdcBitmap);
grfxScreen.ReleaseHdc(hdcScreen);

// convert the Bitmap to BitmapSource
IntPtr hBitmap = bm.GetHbitmap(); // Application crashes here after a while...

//System.Runtime.InteropServices.ExternalException was unhandled
// Message=Generic Error in GDI+.
// Source=System.Drawing
// ErrorCode=-2147467259
// StackTrace:
// at System.Drawing.Bitmap.GetHbitmap(Color background)
// at System.Drawing.Bitmap.GetHbitmap()

if (bms != null) bms = null; // Dispose bms if it holds content
bms = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

// tidy up

// CloseHandle throws SEHException using Framework 4
// CloseHandle(hBitmap);

DeleteObject(hBitmap);
hBitmap = IntPtr.Zero;
bm.Dispose();
hdcBitmap = IntPtr.Zero;
hdcScreen = IntPtr.Zero;
grfxBitmap.Dispose();
grfxScreen.Dispose();
GC.Collect();

}


Подробнее здесь: https://stackoverflow.com/questions/659 ... map-wpf4-c
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»