private void ReleaseCanvas() { if (this.hdc != null) { NativeMethods.SetMapMode(this.hdc, this.oldMapMode); NativeMethods.SetBkColor(this.hdc, this.oldBkColor); this.hdc.Dispose(); this.hdc = null; } if (this.bitmap != null) { this.bitmap.Dispose(); this.bitmap = null; } if (this.hfont != null) { this.hfont.Dispose(); this.hfont = null; } }
/// <summary> /// Initializes a new instance of the <see cref="Canvas"/> class. /// </summary> /// <param name="width">The canvas width.</param> /// <param name="height">The canvas height.</param> public Canvas(int width, int height) { try { // allocate enough to fit all characters this.width = width <= 0 ? 2000 : width; this.height = height; // get handle to device context. this.hdc = NativeMethods.CreateCompatibleDC(new SafeHdcHandle()); if (this.hdc.IsInvalid) { throw new InvalidOperationException(Properties.Resources.E_InvalidCanvasOperation); } // create destination bitmap this.bitmap = NativeMethods.CreateCompatibleBitmap(this.hdc, this.width, this.height); if (this.bitmap.IsInvalid) { throw new InvalidOperationException(Properties.Resources.E_InvalidCanvasOperation); } NativeMethods.SelectObject(this.hdc, this.bitmap); // select color this.oldMapMode = NativeMethods.SetBkMode(this.hdc, NativeMethods.TRANSPARENT); this.oldBkColor = NativeMethods.SetTextColor(this.hdc, System.Drawing.ColorTranslator.ToWin32(System.Drawing.Color.Black)); // erase background this.Clear(); } catch { this.ReleaseCanvas(); throw; } }
public static extern bool ExtTextOut(SafeHdcHandle hdc, int x, int y, int options, ref Rect rect, string s, int count, int[] dx);
public static extern int DrawText(SafeHdcHandle hdc, string s, int count, ref Rect rect, int format);
public static extern int SetBkMode(SafeHdcHandle hdc, int mode);
public static extern int SetBkColor(SafeHdcHandle hdc, int color);
public static extern IntPtr SelectObject(SafeHdcHandle hdc, SafeHandle objectHandle);
public static extern SafeGdiObjectHandle CreateCompatibleBitmap(SafeHdcHandle hdc, int width, int height);
public static extern SafeHdcHandle CreateCompatibleDC(SafeHdcHandle hdc);