// This method wraps the PInvoke to GradientFill. // Parmeters: // gr - The Graphics object we are filling // rc - The rectangle to fill // startColor - The starting color for the fill // endColor - The ending color for the fill // fillDir - The direction to fill // // Returns true if the call to GradientFill succeeded; false // otherwise. public static bool Fill( Graphics gr, Rectangle rc, Color startColor, Color endColor, FillDirection fillDir) { // Initialize the data to be used in the call to GradientFill. Win32Helper.TRIVERTEX[] tva = new Win32Helper.TRIVERTEX[2]; tva[0] = new Win32Helper.TRIVERTEX(rc.X, rc.Y, startColor); tva[1] = new Win32Helper.TRIVERTEX(rc.Right, rc.Bottom, endColor); Win32Helper.GRADIENT_RECT[] gra = new Win32Helper.GRADIENT_RECT[] { new Win32Helper.GRADIENT_RECT(0, 1)}; // Get the hDC from the Graphics object. IntPtr hdc = gr.GetHdc(); // PInvoke to GradientFill. bool b; b = Win32Helper.GradientFill( hdc, tva, (uint)tva.Length, gra, (uint)gra.Length, (uint)fillDir); System.Diagnostics.Debug.Assert(b, string.Format( "GradientFill failed: {0}", System.Runtime.InteropServices.Marshal.GetLastWin32Error())); // Release the hDC from the Graphics object. gr.ReleaseHdc(hdc); return b; }
public GDIMemoryContext(Graphics compatibleTo, int width, int height) { if (compatibleTo == null || width <= 0 || height <= 0) throw new ArgumentException("Arguments are unacceptable"); IntPtr tmp = compatibleTo.GetHdc(); bool failed = true; do { if ((fDC = NativeMethods.CreateCompatibleDC(tmp)) == IntPtr.Zero) break; if ((fBitmap = NativeMethods.CreateCompatibleBitmap(tmp, width, height)) == IntPtr.Zero) { NativeMethods.DeleteDC(fDC); break; } fStockMonoBmp = NativeMethods.SelectObject(fDC, fBitmap); if (fStockMonoBmp == IntPtr.Zero) { NativeMethods.DeleteObject(fBitmap); NativeMethods.DeleteDC(fDC); } else failed = false; } while (false); compatibleTo.ReleaseHdc(tmp); if (failed) throw new SystemException("GDI error occured while creating context"); this.gdiPlusContext = Graphics.FromHdc(this.fDC); this.fWidth = width; this.fHeight = height; }
public override void Render(int page, Graphics graphics, float dpiX, float dpiY, Rectangle bounds) { _document.CurrentPage = page + 1; _document.RenderDPI = dpiX; _document.ClientBounds = bounds; _document.CurrentX = -bounds.Left; _document.CurrentY = -bounds.Top; var hdc = graphics.GetHdc(); try { // xPDF uses the control to get sizing information. We use // a dummy control to satisfy this requirement. _dummyControl.Size = new Size(bounds.Width, 1); _document.FitToWidth(_dummyControl.Handle); _document.RenderPage(_dummyControl.Handle); _document.DrawPageHDC(hdc); } finally { graphics.ReleaseHdc(hdc); } }
public static void DrawText(System.Drawing.Graphics graphics, string text, System.Drawing.Font font, System.Drawing.Color foreColor, System.Drawing.Color backColor, System.Drawing.Rectangle bounds, Skybound.Windows.Forms.TextFormatFlags formatFlags) { if ((text == null) || (text.Length == 0) || (graphics == null) || (font == null) || bounds.Size == System.Drawing.Size.Empty || foreColor.Equals(System.Drawing.Color.Empty) || foreColor.Equals(System.Drawing.Color.Transparent)) { return; } System.IntPtr intPtr1 = graphics.GetHdc(); try { System.IntPtr intPtr2 = Skybound.Windows.Forms.TextRenderer.GetCachedFont(font); System.IntPtr intPtr3 = Skybound.Windows.Forms.TextRenderer.SelectObject(intPtr1, intPtr2); if (backColor.Equals(System.Drawing.Color.Empty) || backColor.Equals(System.Drawing.Color.Transparent)) { Skybound.Windows.Forms.TextRenderer.SetBkMode(intPtr1, 1); } else { Skybound.Windows.Forms.TextRenderer.SetBkMode(intPtr1, 2); Skybound.Windows.Forms.TextRenderer.SetBkColor(intPtr1, System.Drawing.ColorTranslator.ToWin32(backColor)); } int i = Skybound.Windows.Forms.TextRenderer.GetTextColor(intPtr1); Skybound.Windows.Forms.TextRenderer.SetTextColor(intPtr1, System.Drawing.ColorTranslator.ToWin32(foreColor)); Skybound.Windows.Forms.TextRenderer.RECT rect = new Skybound.Windows.Forms.TextRenderer.RECT(bounds); Skybound.Windows.Forms.TextRenderer.DrawText(intPtr1, text, text.Length, ref rect, (int)formatFlags); Skybound.Windows.Forms.TextRenderer.SetTextColor(intPtr1, i); Skybound.Windows.Forms.TextRenderer.SelectObject(intPtr1, intPtr3); } finally { graphics.ReleaseHdc(intPtr1); } }
/// <summary> /// 对一个WebBrowser进行截图 /// </summary> /// <param name="targetBrowser">我这里用的是Forms的WebBrowser,如果是wpf的,请自己改成Controls并调整参数</param> /// <returns></returns> public static ImageSource BrowserSnapShot(System.Windows.Controls.WebBrowser targetBrowser) { try { // 获取宽高 int screenWidth = (int)targetBrowser.ActualWidth; int screenHeight = (int)targetBrowser.ActualHeight; IntPtr myIntptr = targetBrowser.Handle; int hwndInt = myIntptr.ToInt32(); IntPtr hwnd = myIntptr; //创建图形 System.Drawing.Bitmap bm = new System.Drawing.Bitmap(screenWidth, screenHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm); IntPtr hdc = g.GetHdc(); //调用api 把hwnd的内容用图形绘制到hdc 如果你有代码洁癖 可以不使用api 使用g.CopyFromScreen,请自行研究 bool result = PrintWindow(hwnd, hdc, 0); g.ReleaseHdc(hdc); g.Flush(); if (result == true) //成功 转换并返回ImageSource { ImageSourceConverter imageSourceConverter = new ImageSourceConverter(); MemoryStream stream = new MemoryStream(); bm.Save(stream, System.Drawing.Imaging.ImageFormat.Png); return((ImageSource)imageSourceConverter.ConvertFrom(stream)); } } catch { } return(null); }
public static void DrawRoundRect(Graphics g, int x, int y, int width, int height, RoundRectColors colors) { IntPtr hdc = g.GetHdc(); const int ROUND_SIZE = 3; //3*3�s�N�Z���͎��O�ŕ`�� IntPtr pen = Win32.CreatePen(0, 1, colors.border_color); Win32.SelectObject(hdc, pen); //�� Win32.MoveToEx(hdc, x + ROUND_SIZE, y); Win32.LineTo(hdc, x + width - ROUND_SIZE + 1, y); //�� Win32.MoveToEx(hdc, x + ROUND_SIZE, y + height); Win32.LineTo(hdc, x + width - ROUND_SIZE + 1, y + height); //�� Win32.MoveToEx(hdc, x, y + ROUND_SIZE); Win32.LineTo(hdc, x, y + height - ROUND_SIZE + 1); //�E Win32.MoveToEx(hdc, x + width, y + ROUND_SIZE); Win32.LineTo(hdc, x + width, y + height - ROUND_SIZE + 1); Win32.DeleteObject(pen); DrawRoundCorner(hdc, x, y, 1, 1, colors); //���� DrawRoundCorner(hdc, x + width, y, -1, 1, colors); //�E�� DrawRoundCorner(hdc, x, y + height, 1, -1, colors); //���� DrawRoundCorner(hdc, x + width, y + height, -1, -1, colors); //�E�� g.ReleaseHdc(hdc); }
public MemoryBuffer(int width, int height) { m_bitmap = new Bitmap(width, height); // create graphics memory buffer m_graphics = Graphics.FromImage(m_bitmap); m_graphics.GetHdc(); }
public static void DrawRoundRect(Graphics g, int x, int y, int width, int height, RoundRectColors colors) { IntPtr hdc = g.GetHdc(); const int ROUND_SIZE = 3; //3*3ピクセルは自前で描画 IntPtr pen = Win32.CreatePen(0, 1, colors.border_color); Win32.SelectObject(hdc, pen); //上 Win32.MoveToEx(hdc, x + ROUND_SIZE, y); Win32.LineTo(hdc, x + width - ROUND_SIZE + 1, y); //下 Win32.MoveToEx(hdc, x + ROUND_SIZE, y + height); Win32.LineTo(hdc, x + width - ROUND_SIZE + 1, y + height); //左 Win32.MoveToEx(hdc, x, y + ROUND_SIZE); Win32.LineTo(hdc, x, y + height - ROUND_SIZE + 1); //右 Win32.MoveToEx(hdc, x + width, y + ROUND_SIZE); Win32.LineTo(hdc, x + width, y + height - ROUND_SIZE + 1); Win32.DeleteObject(pen); DrawRoundCorner(hdc, x, y, 1, 1, colors); //左上 DrawRoundCorner(hdc, x + width, y, -1, 1, colors); //右上 DrawRoundCorner(hdc, x, y + height, 1, -1, colors); //左下 DrawRoundCorner(hdc, x + width, y + height, -1, -1, colors); //右下 g.ReleaseHdc(hdc); }
public static void Stretch(Graphics g, Rectangle rcSrc, Rectangle dest, BitmapData bd) { var ar = new byte[Marshal.SizeOf(typeof(BITMAPINFOHEADER))+12]; unsafe { fixed (byte* par = ar) { var pInfo = (BITMAPINFOHEADER*)par; pInfo->Init(); pInfo->biWidth = bd.Width; pInfo->biHeight = -bd.Height; pInfo->biPlanes = 1; pInfo->biBitCount = 32; pInfo->biCompression = BitmapCompression.BI_BITFIELDS; pInfo->biSizeImage = (uint)(bd.Stride * bd.Height); UInt32* masks = (UInt32*)(par + Marshal.SizeOf(typeof(BITMAPINFOHEADER))); masks[0] = 0xFF0000; masks[1] = 0xFF00; masks[2] = 0xFF; IntPtr hdc = g.GetHdc(); try { int r = Api.StretchDIBits(hdc, dest.Left, dest.Top, dest.Width, dest.Height, rcSrc.Left, rcSrc.Top, rcSrc.Width, rcSrc.Height, bd.Scan0, ref *pInfo, 0, RasterOp.SRCCOPY); Api.Win32Check(Api.GDI_ERROR != r); } finally { g.ReleaseHdc(hdc); } } } }
private static void AnimateZoomIn(Graphics formGraphics, IntPtr[] nativeBitmapHandles, Size size) { // Create device contexts. IntPtr targetDC = formGraphics.GetHdc(); IntPtr sourceDC = NativeMethods.GDI32.CreateCompatibleDC(targetDC); // Capture sourceDC's original empty HBitmap and select first frame for drawing. IntPtr emptyNativeBitmapHandle = NativeMethods.GDI32.SelectObject(sourceDC, nativeBitmapHandles[0]); // Draw animation frames to form. for (int c = 1; c < 90; c++) { NativeMethods.BitBlockTransfer(targetDC, 0, 0, size.Width, size.Height, sourceDC, 0, 0); NativeMethods.GDI32.SelectObject(sourceDC, nativeBitmapHandles[c]); Thread.Sleep(5); } // Draw final frame. NativeMethods.BitBlockTransfer(targetDC, 0, 0, size.Width, size.Height, sourceDC, 0, 0); // Clean up. NativeMethods.GDI32.SelectObject(sourceDC, emptyNativeBitmapHandle); NativeMethods.GDI32.DeleteDC(sourceDC); formGraphics.ReleaseHdc(targetDC); }
public AlphaLayerControl(Graphics parentGraphics, Size size, byte alphaVal) { try { _alphaImage = new Bitmap(size.Width, size.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb565); using (Graphics gx = Graphics.FromImage(_alphaImage)) { IntPtr hdcDst = gx.GetHdc(); IntPtr hdcSrc = parentGraphics.GetHdc(); Win32.BlendFunction blendFunction = new Win32.BlendFunction(); blendFunction.BlendOp = (byte)Win32.BlendOperation.AC_SRC_OVER; // Only supported blend operation blendFunction.BlendFlags = (byte)Win32.BlendFlags.Zero; // Documentation says put 0 here blendFunction.SourceConstantAlpha = alphaVal;// Constant alpha factor blendFunction.AlphaFormat = (byte)0; // Don't look for per pixel alpha Win32.AlphaBlend(hdcDst, 0, 0, _alphaImage.Width, _alphaImage.Height, hdcSrc, 0, 0, _alphaImage.Width, _alphaImage.Height, blendFunction); gx.ReleaseHdc(hdcDst); // Required cleanup to GetHdc() parentGraphics.ReleaseHdc(hdcSrc); // Required cleanup to GetHdc() } } catch { GC.Collect(); _alphaImage = new Bitmap(1, 1); } }
private void DrawStatic(PaintEventArgs e) { using (System.Drawing.Graphics graphics = e.Graphics) using (Win32Surface surface = new Win32Surface(graphics.GetHdc())) using (Context context = new Context(surface)) { //clear the background to white context.SetSourceRGB(1, 1, 1); context.Paint(); //stroke the bug context.LineWidth = 2.0; context.SetSourceColor(this.bugColor); context.MoveTo(7.0, 64.0); context.CurveTo(1.0, 47.0, 2.0, 46.0, 9.0, 51.0); context.MoveTo(25.0, 80.0); context.CurveTo(10.0, 73.0, 11.0, 70.0, 14.0, 63.0); context.MoveTo(10.0, 41.0); context.CurveTo(2.0, 36.0, 1.0, 33.0, 1.0, 26.0); context.LineWidth = 1.0; context.MoveTo(1.0, 26.0); context.CurveTo(5.0, 23.0, 7.0, 18.0, 12.0, 17.0); context.LineTo(12.0, 14.0); context.Stroke(); context.MoveTo(30.0, 74.0); context.CurveTo(14.0, 64.0, 10.0, 48.0, 11.0, 46.0); context.LineTo(10.0, 45.0); context.LineTo(10.0, 40.0); context.CurveTo(13.0, 37.0, 15.0, 35.0, 19.0, 34.0); context.Stroke(); } }
private void DoDraw() { EventsHelper.Fire(_drawing, this, EventArgs.Empty); CodeClock clock = new CodeClock(); clock.Start(); if (this.Surface != null) { System.Drawing.Graphics graphics = this.CreateGraphics(); this.Surface.WindowID = this.Handle; this.Surface.ContextID = graphics.GetHdc(); this.Surface.ClientRectangle = this.ClientRectangle; this.Surface.ClipRectangle = this.ClientRectangle; DrawArgs args = new DrawArgs(this.Surface, new WinFormsScreenProxy(Screen.FromControl(this)), DrawMode.Render) { Dpi = Dpi }; _isDrawing = true; try { _tile.Draw(args); _lastRenderExceptionMessage = null; } catch (Exception ex) { Platform.Log(LogLevel.Error, ex, "An error has occured while rendering the contents of a tile."); _lastRenderExceptionMessage = ex is RenderingException ? ((RenderingException)ex).UserMessage : ex.Message; // we cannot simply pass the existing Graphics because we haven't released its hDC yet // if we do, we'll get a "Object is currently in use elsewhere" exception DrawErrorMessage(_lastRenderExceptionMessage, Surface.ContextID, ClientRectangle); } finally { graphics.ReleaseHdc(this.Surface.ContextID); graphics.Dispose(); _isDrawing = false; } } //Cause the tile to paint/refresh. Invalidate(); Update(); clock.Stop(); string str = String.Format("TileControl.Draw: {0}, {1}\n", clock.ToString(), this.Size.ToString()); Trace.Write(str); }
internal static void GetScreenDpi(out int dpiX, out int dpiY) { using (Bitmap image = new Bitmap(2, 2)) { using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(image)) { IntPtr hdc = graphics.GetHdc(); try { int deviceCaps = Microsoft.ReportingServices.Rendering.RichText.Win32.GetDeviceCaps(hdc, 88); int deviceCaps2 = Microsoft.ReportingServices.Rendering.RichText.Win32.GetDeviceCaps(hdc, 90); int deviceCaps3 = Microsoft.ReportingServices.Rendering.RichText.Win32.GetDeviceCaps(hdc, 8); int deviceCaps4 = Microsoft.ReportingServices.Rendering.RichText.Win32.GetDeviceCaps(hdc, 10); int deviceCaps5 = Microsoft.ReportingServices.Rendering.RichText.Win32.GetDeviceCaps(hdc, 118); int deviceCaps6 = Microsoft.ReportingServices.Rendering.RichText.Win32.GetDeviceCaps(hdc, 117); dpiX = (int)Math.Floor(1.0 * (double)deviceCaps * (double)deviceCaps5 / (double)deviceCaps3); dpiY = (int)Math.Floor(1.0 * (double)deviceCaps2 * (double)deviceCaps6 / (double)deviceCaps4); } finally { graphics.ReleaseHdc(hdc); } } } }
public static void BitBlt(Graphics g, IntPtr hObject, Rectangle srcRect, Point destPoint) { IntPtr pTarget = g.GetHdc(); try { IntPtr pSource = Gdi32.CreateCompatibleDC(pTarget); try { IntPtr pOrig = Gdi32.SelectObject(pSource, hObject); try { Gdi32.BitBlt(pTarget, destPoint.X, destPoint.Y, srcRect.Width, srcRect.Height, pSource, srcRect.X, srcRect.Y, Gdi32.TernaryRasterOperations.SRCCOPY); } finally { Gdi32.SelectObject(pSource, pOrig); } } finally { Gdi32.DeleteDC(pSource); } } finally { g.ReleaseHdc(pTarget); } }
/// <summary> /// Generates the text metrics. /// </summary> /// <param name="graphics">The graphics.</param> /// <param name="font">The font.</param> /// <returns>TEXTMETRIC.</returns> private TEXTMETRIC GenerateTextMetrics( System.Drawing.Graphics graphics, Font font) { IntPtr hDC = IntPtr.Zero; TEXTMETRIC textMetric; IntPtr hFont = IntPtr.Zero; try { hDC = graphics.GetHdc(); hFont = font.ToHfont(); IntPtr hFontDefault = SelectObject(hDC, hFont); bool result = GetTextMetrics(hDC, out textMetric); SelectObject(hDC, hFontDefault); } finally { if (hFont != IntPtr.Zero) { DeleteObject(hFont); } if (hDC != IntPtr.Zero) { graphics.ReleaseHdc(hDC); } } return(textMetric); }
public void DrawXORRectangle(System.Drawing.Graphics grp, int X1, int Y1, int X2, int Y2) { // Extract the Win32 HDC from the Graphics object supplied. IntPtr hdc = grp.GetHdc(); // Create a pen with a dotted style to draw the border of the // rectangle. IntPtr gdiPen = CreatePen(penStyle, width, Col); // Set the ROP cdrawint mode to XOR. SetROP2(hdc, R2_XORPEN); // Select the pen into the device context. IntPtr oldPen = SelectObject(hdc, gdiPen); // Create a stock NULL_BRUSH brush and select it into the device // context so that the rectangle isn't filled. IntPtr oldBrush = SelectObject(hdc, GetStockObject(NULL_BRUSH)); // Now XOR the hollow rectangle on the Graphics object with // a dotted outline. Rectangle(hdc, X1, Y1, X2, Y2); // Put the old stuff back where it was. SelectObject(hdc, oldBrush); // no need to delete a stock object SelectObject(hdc, oldPen); DeleteObject(gdiPen); // but we do need to delete the pen // Return the device context to Windows. grp.ReleaseHdc(hdc); }
public void Draw(Graphics graphics, Rectangle layoutArea) { //Calculate the area to render. SafeNativeMethods.RECT rectLayoutArea; rectLayoutArea.Top = (int)(layoutArea.Top * anInch); rectLayoutArea.Bottom = (int)(layoutArea.Bottom * anInch); rectLayoutArea.Left = (int)(layoutArea.Left * anInch); rectLayoutArea.Right = (int)(layoutArea.Right * anInch); IntPtr hdc = graphics.GetHdc(); SafeNativeMethods.FORMATRANGE fmtRange; fmtRange.chrg.cpMax = -1; //Indicate character from to character to fmtRange.chrg.cpMin = 0; fmtRange.hdc = hdc; //Use the same DC for measuring and rendering fmtRange.hdcTarget = hdc; //Point at printer hDC fmtRange.rc = rectLayoutArea; //Indicate the area on page to print fmtRange.rcPage = rectLayoutArea; //Indicate size of page IntPtr wParam = IntPtr.Zero; wParam = new IntPtr(1); //Get the pointer to the FORMATRANGE structure in memory IntPtr lParam = IntPtr.Zero; lParam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange)); Marshal.StructureToPtr(fmtRange, lParam, false); SafeNativeMethods.SendMessage(this.Handle, SafeNativeMethods.EM_FORMATRANGE, wParam, lParam); //Free the block of memory allocated Marshal.FreeCoTaskMem(lParam); //Release the device context handle obtained by a previous call graphics.ReleaseHdc(hdc); }
internal void BeginRender(Graphics g) { if (m_hdc != IntPtr.Zero) throw new Exception("EndRender first."); m_oG = g; m_hdc = m_oG.GetHdc(); }
protected override bool OnExposeEvent(Gdk.EventExpose args) { using (Context cg = Gdk.CairoHelper.Create(args.Window)) { Win32GDI GDI_Win32 = Win32GDI.getInstance(); if (GDI_Win32.isAvailable()) { System.Drawing.Graphics wg = Gtk.DotNet.Graphics.FromDrawable(this.GdkWindow, true); IntPtr hdc = wg.GetHdc(); int i = 0; int n = 3; int w = 16; int h = 16; Rect[] rects = new Rect[n]; /* Test Case 1 */ rects[i].x1 = 0; rects[i].y1 = 0; rects[i].x2 = w; rects[i].y2 = h; i++; /* Test Case 2 */ rects[i].x1 = w * i + 3; rects[i].y1 = 0; rects[i].x2 = w * (i + 1) - 3; rects[i].y2 = h; i++; /* Test Case 3 */ rects[i].x1 = w * i; rects[i].y1 = 0 + 3; rects[i].x2 = w * (i + 1); rects[i].y2 = h - 3; i++; /* Fill Area with White */ cg.Color = new Cairo.Color(255, 255, 255); Cairo.Rectangle rect = new Cairo.Rectangle(0, 0, n * w, h); cg.Rectangle(rect); cg.Fill(); cg.Stroke(); IntPtr blackSolidBrush = GDI_Win32.CreateSolidBrush(0); IntPtr oldBrush = GDI_Win32.SelectObject(hdc, blackSolidBrush); for (i = 0; i < n; i++) { GDI_Win32.Ellipse(hdc, rects[i].x1, rects[i].y1, rects[i].x2, rects[i].y2); dumpText += "unsigned char ellipse_case_" + (i + 1) + "[" + w * h + "] = \n"; dumpText += dumpPixelArea(GDI_Win32, hdc, i * w, 0, w, h) + "\n"; } } } return(true); }
private BufferedGraphics AllocBuffer(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle) { if (Interlocked.CompareExchange(ref this.busy, 1, 0) != 0) { return this.AllocBufferInTempManager(targetGraphics, targetDC, targetRectangle); } this.targetLoc = new Point(targetRectangle.X, targetRectangle.Y); try { Graphics graphics; if (targetGraphics != null) { IntPtr hdc = targetGraphics.GetHdc(); try { graphics = this.CreateBuffer(hdc, -this.targetLoc.X, -this.targetLoc.Y, targetRectangle.Width, targetRectangle.Height); } finally { targetGraphics.ReleaseHdcInternal(hdc); } } else { graphics = this.CreateBuffer(targetDC, -this.targetLoc.X, -this.targetLoc.Y, targetRectangle.Width, targetRectangle.Height); } this.buffer = new BufferedGraphics(graphics, this, targetGraphics, targetDC, this.targetLoc, this.virtualSize); } catch { this.busy = 0; throw; } return this.buffer; }
private DeviceContext(Graphics graphics, ScriptMetricsCache scriptMetricsCache) { this.graphics = graphics; this.scriptMetricsCache = scriptMetricsCache; HDC = graphics != null ? graphics.GetHdc() : NativeMethods.GetDC(IntPtr.Zero); }
private void pnCanvas_Paint(object sender, PaintEventArgs e) { if (isPainting) { CommonGraphics lib; System.Drawing.Graphics g = e.Graphics; if (radioGdi.Checked) { lib = new GdiPlus(g); } else { Surface s = new Win32Surface(g.GetHdc()); Context c = new Context(s); lib = new Cairo(c); } foreach (Shape shape in shapes) { shape.draw(lib); } diagram.draw(lib); g.Dispose(); } }
public ImageSource GetWindowImage(IntPtr hWnd, FormsDraw.Rectangle bounds) { try { using (FormsDraw.Bitmap result = new FormsDraw.Bitmap(bounds.Width, bounds.Height)) { //creates a new Bitmap which will contain the window's image using (FormsDraw.Graphics MemG = FormsDraw.Graphics.FromImage(result)) { //makes a Graphics from the Bitmap whose HDC will hold the window's RAW image IntPtr dc = MemG.GetHdc(); //gets the Bitmap's HDC try { PrintWindow(hWnd, dc, 0);//Writes the window's image to the HDC created above } finally { MemG.ReleaseHdc(dc); } var handle = result.GetHbitmap(); try { return(System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); } finally { DeleteObject(handle); } } } } catch { /*this try/catch block is only here to hide any function's errors :P (bad practice? where?) * It also creates an empty bitmap to avoid returning null and thus prevent the entire program from going to hell */ FormsDraw.Bitmap nullbmp = new FormsDraw.Bitmap(bounds.Width, bounds.Height); var handle = nullbmp.GetHbitmap(); return(System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); } }
private static IntPtr BeginDraw(System.Drawing.Bitmap bmp, System.Drawing.Graphics graphics, int x1, int y1, int x2, int y2, bool dash, out int oldRop, out IntPtr img, out IntPtr oldpen) { var gHdc = graphics.GetHdc(); var hdc = CreateCompatibleDC(gHdc); graphics.ReleaseHdc(hdc); img = bmp.GetHbitmap(); SelectObject(hdc, img); oldpen = IntPtr.Zero; if (dash) { var pen = CreatePen(PenStyle.PS_DASH, 1, 0); oldpen = SelectObject(hdc, pen); } oldRop = SetROP2(hdc, (int)BinaryRasterOperations.R2_NOTXORPEN); // Switch to inverted mode. (XOR) SetGraphicsMode(hdc, (int)GraphicsMode.GM_ADVANCED); XFORM transform = graphics.Transform; SetWorldTransform(hdc, ref transform); return(hdc); }
public void Update(Graphics g, string text, Font font, Padding internalBounds, Rectangle bounds, Color color, TextFormatFlags formatFlags, IThemeTextOption[] options) { IntPtr compatHdc = this._TextHDC; if (bounds.Equals(_TextHDCBounds)) { //Same bounds, reuse HDC and Clear it IntPtr hClearBrush = Native.GDI.CreateSolidBrush(ColorTranslator.ToWin32(Color.Black)); Native.RECT cleanRect = new Native.RECT(bounds); Native.GDI.FillRect(compatHdc, ref cleanRect, hClearBrush); Native.GDI.DeleteObject(hClearBrush); } else { //Other bounds, create new HDC IntPtr outputHdc = g.GetHdc(); IntPtr DIB; compatHdc = CreateNewHDC(outputHdc, bounds, out DIB); //Store new data _TextHDC = compatHdc; _TextHDCBounds = bounds; //Clear up CleanUpHDC(DIB); g.ReleaseHdc(outputHdc); } DrawOnHDC(compatHdc, text, font, internalBounds, bounds, color, formatFlags, options); }
public static Size GetTextSize(Graphics graphics, string text, Font font, ref Rectangle rc, DrawTextFormatFlags drawFlags) { IntPtr hdc = IntPtr.Zero; if ( graphics != null ) { // Get device context from the graphics passed in hdc = graphics.GetHdc(); } else { // Get screen device context hdc = WindowsAPI.GetDC(IntPtr.Zero); } IntPtr fontHandle = font.ToHfont(); IntPtr currentFontHandle = WindowsAPI.SelectObject(hdc, fontHandle); Win32.RECT rect = new Win32.RECT(); rect.left = rc.Left; rect.right = rc.Right; rect.top = rc.Top; rect.bottom = rc.Bottom; WindowsAPI.DrawText(hdc, text, text.Length, ref rect, (int)drawFlags); WindowsAPI.SelectObject(hdc, currentFontHandle); WindowsAPI.DeleteObject(fontHandle); if ( graphics != null ) graphics.ReleaseHdc(hdc); else WindowsAPI.ReleaseDC(IntPtr.Zero, hdc); return new Size(rect.right - rect.left, rect.bottom - rect.top); }
private void GeneratePreview() { if ((picStylePreview == null) || (g_pGxView == null)) { return; } tagRECT r = new tagRECT(); r.bottom = picStylePreview.ClientSize.Height; r.top = 0; r.right = picStylePreview.ClientSize.Width; r.left = 0; bmpPreview = new Bitmap(r.right, r.bottom); System.Drawing.Graphics GrpObj = Graphics.FromImage(bmpPreview); try { g_pGxView.PreviewItem((Int64)GrpObj.GetHdc(), r); GrpObj.ReleaseHdc(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { GrpObj.Dispose(); } picStylePreview.Image = bmpPreview; }
public static void DrawRect(Graphics graphics, int x0, int y0, int x1, int y1, Color colour) { IntPtr hdc = graphics.GetHdc(); try { IntPtr pen = CreatePen(PenStyle.PS_SOLID, 1, (uint)ColorTranslator.ToWin32(colour)); IntPtr oldpen = SelectObject(hdc, pen); try { MoveToEx(hdc, x0, y0, IntPtr.Zero); POINT[] points = new POINT[] { new Point(x0, y0), new POINT(x0, y0), new POINT(x1, y0), new POINT(x1, y1), new POINT(x0, y1), new POINT(x0, y0) }; PolylineTo(hdc, points, (uint)points.Length); } finally { DeleteObject(SelectObject(hdc, oldpen)); } } finally { graphics.ReleaseHdc(); } }
public static Size GetTextSize(Graphics graphics, string text, Font font) { IntPtr hdc = IntPtr.Zero; if ( graphics != null ) { // Get device context from the graphics passed in hdc = graphics.GetHdc(); } else { // Get screen device context hdc = WindowsAPI.GetDC(IntPtr.Zero); } IntPtr fontHandle = font.ToHfont(); IntPtr currentFontHandle = WindowsAPI.SelectObject(hdc, fontHandle); Win32.RECT rect = new Win32.RECT(); rect.left = 0; rect.right = 0; rect.top = 0; rect.bottom = 0; WindowsAPI.DrawText(hdc, text, text.Length, ref rect, (int)(DrawTextFormatFlags.DT_SINGLELINE | DrawTextFormatFlags.DT_LEFT | DrawTextFormatFlags.DT_CALCRECT)); WindowsAPI.SelectObject(hdc, currentFontHandle); WindowsAPI.DeleteObject(fontHandle); if ( graphics != null ) graphics.ReleaseHdc(hdc); else WindowsAPI.ReleaseDC(IntPtr.Zero, hdc); return new Size(rect.right - rect.left, rect.bottom - rect.top); }
public static void DrawThemeTextActive( Graphics aGraph, string aText, Point aLocation, SUxTextProperties aProp ) { IntPtr lPriHdc = aGraph.GetHdc(); VisualStyleRenderer lRenderer = new VisualStyleRenderer(VisualStyleElement.Window.Caption.Active); DTTOPTS lOpts = new DTTOPTS(); lOpts.dwSize = Marshal.SizeOf(lOpts); lOpts.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE | DTT_TEXTCOLOR; lOpts.crText = ColorTranslator.ToWin32(aProp.color); lOpts.iGlowSize = aProp.glowSize; RECT ltBounds = new RECT(0, 0, aProp.bounds.Width, aProp.bounds.Height); DrawThemeTextEx( lRenderer.Handle, lPriHdc, 0, 0, aText, -1, (int)(aProp.flags), ref ltBounds, ref lOpts ); }
protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); using (System.Drawing.Graphics graphics = e.Graphics) { using (Win32Surface surface = new Win32Surface(graphics.GetHdc())) { using (Context context = new Context(surface)) { context.LineWidth = 2.0; context.SetSourceColor(this.bugColor); context.MoveTo(7.0, 64.0); context.CurveTo(1.0, 47.0, 2.0, 46.0, 9.0, 51.0); context.MoveTo(25.0, 80.0); context.CurveTo(10.0, 73.0, 11.0, 70.0, 14.0, 63.0); context.MoveTo(10.0, 41.0); context.CurveTo(2.0, 36.0, 1.0, 33.0, 1.0, 26.0); context.LineWidth = 1.0; context.MoveTo(1.0, 26.0); context.CurveTo(5.0, 23.0, 7.0, 18.0, 12.0, 17.0); context.LineTo(12.0, 14.0); context.Stroke(); context.MoveTo(30.0, 74.0); context.CurveTo(14.0, 64.0, 10.0, 48.0, 11.0, 46.0); context.LineTo(10.0, 45.0); context.LineTo(10.0, 40.0); context.CurveTo(13.0, 37.0, 15.0, 35.0, 19.0, 34.0); context.Stroke(); } } } }
public static bool Fill( Graphics gr, Rectangle rc, Color startColor, Color endColor, FillDirection fillDir) { if (System.Environment.OSVersion.Platform != PlatformID.WinCE) { using (SolidBrush br = new SolidBrush(startColor)) { gr.FillRectangle(br, rc); } return true; } // 頂点の座標と色を指定 Win32Helper.TRIVERTEX[] tva = new Win32Helper.TRIVERTEX[2]; tva[0] = new Win32Helper.TRIVERTEX(rc.X, rc.Y, startColor); tva[1] = new Win32Helper.TRIVERTEX(rc.Right, rc.Bottom, endColor); // どのTRIVERTEXの値を使用するかインデックスを指定 Win32Helper.GRADIENT_RECT[] gra = new Win32Helper.GRADIENT_RECT[] { new Win32Helper.GRADIENT_RECT(0, 1) }; // GradientFill関数の呼び出し IntPtr hdc = gr.GetHdc(); bool b = Win32Helper.GradientFill( hdc, tva, (uint)tva.Length, gra, (uint)gra.Length, (uint)fillDir); gr.ReleaseHdc(hdc); return b; }
public static Size GetTextSize(Graphics graphics, string text, Font font) { IntPtr hdc = IntPtr.Zero; if ( graphics != null ) { // Get device context from the graphics passed in hdc = graphics.GetHdc(); } else { // Get screen device context hdc = APIsGdi.GetDC(IntPtr.Zero); } IntPtr fontHandle = font.ToHfont(); IntPtr currentFontHandle = APIsGdi.SelectObject(hdc, fontHandle); APIsStructs.RECT rect = new APIsStructs.RECT(); rect.left = 0; rect.right = 0; rect.top = 0; rect.bottom = 0; APIsUser32.DrawText(hdc, text, text.Length, ref rect, APIsEnums.DrawTextFormatFlags.SINGLELINE | APIsEnums.DrawTextFormatFlags.LEFT | APIsEnums.DrawTextFormatFlags.CALCRECT); APIsGdi.SelectObject(hdc, currentFontHandle); APIsGdi.DeleteObject(fontHandle); if(graphics != null) graphics.ReleaseHdc(hdc); else APIsUser32.ReleaseDC(IntPtr.Zero, hdc); return new Size(rect.right - rect.left, rect.bottom - rect.top); }
/// <summary> /// Measure a multiline string /// </summary> public static Size MeasureString(Graphics gr, Font font, string text, int width) { if (text == null) return new Size(1, 1); Rect bounds = new Rect() { Left = 0, Right = width, Bottom = 1, Top = 0 }; IntPtr hDc = gr.GetHdc(); try { int flags = DTCALCRECT | DTWORDBREAK; IntPtr controlFont = font.ToHfont(); IntPtr originalObject = SelectObject(hDc, controlFont); try { DrawText(hDc, text, text.Length, ref bounds, flags); } finally { SelectObject(hDc, originalObject); // Release resources } } finally { gr.ReleaseHdc(hDc); } return new Size(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top); }
public static void DrawLine(Graphics g, Pen pen, int x1, int y1, int x2, int y2) { if (g == null) { throw new ArgumentNullException("g"); } if (pen == null) { throw new ArgumentNullException("pen"); } IntPtr hDC = g.GetHdc(); IntPtr hPen = Gdi32.CreatePen(pen); IntPtr oldBrush = Gdi32.SelectObject(hDC, Gdi32.GetStockObject(WinGdi.NULL_BRUSH)); IntPtr oldPen = Gdi32.SelectObject(hDC, hPen); Gdi32.MoveTo(hDC, x1, y1); Gdi32.LineTo(hDC, x2, y2); Gdi32.SelectObject(hDC, oldBrush); Gdi32.SelectObject(hDC, oldPen); Gdi32.DeleteObject(hPen); g.ReleaseHdc(hDC); }
public int Print(int charFrom, int charTo, System.Drawing.RectangleF marginBounds, System.Drawing.RectangleF pageBounds, System.Drawing.Graphics g) { this.anInch = 1440.0 / (double)g.DpiX; PrintableRtf.RECT rc; rc.Top = (int)((double)marginBounds.Top * this.anInch); rc.Bottom = (int)((double)marginBounds.Bottom * this.anInch); rc.Left = (int)((double)marginBounds.Left * this.anInch); rc.Right = (int)((double)marginBounds.Right * this.anInch); PrintableRtf.RECT rcPage; rcPage.Top = (int)((double)pageBounds.Top * this.anInch); rcPage.Bottom = (int)((double)pageBounds.Bottom * this.anInch); rcPage.Left = (int)((double)pageBounds.Left * this.anInch); rcPage.Right = (int)((double)pageBounds.Right * this.anInch); IntPtr hdc = g.GetHdc(); PrintableRtf.FORMATRANGE fORMATRANGE; fORMATRANGE.chrg.cpMax = charTo; fORMATRANGE.chrg.cpMin = charFrom; fORMATRANGE.hdc = hdc; fORMATRANGE.hdcTarget = hdc; fORMATRANGE.rc = rc; fORMATRANGE.rcPage = rcPage; IntPtr intPtr = IntPtr.Zero; IntPtr zero = IntPtr.Zero; zero = new IntPtr(1); IntPtr intPtr2 = IntPtr.Zero; intPtr2 = Marshal.AllocCoTaskMem(Marshal.SizeOf(fORMATRANGE)); Marshal.StructureToPtr(fORMATRANGE, intPtr2, false); intPtr = PrintableRtf.SendMessage(base.Handle, 1081, zero, intPtr2); Marshal.FreeCoTaskMem(intPtr2); g.ReleaseHdc(hdc); return(intPtr.ToInt32()); }
void PrepareCharacterMapBlackOnWhite(char[] buffer) { //----------------------------------------------------------------------- IntPtr gxdc = gx.GetHdc(); int len = buffer.Length; //draw each character int curX = 0; int curY = 0; //1. clear with white color, MyWin32.PatBlt(gxdc, 0, 0, width, height, MyWin32.WHITENESS); //2. transparent background MyWin32.SetBkMode(gxdc, MyWin32._SetBkMode_TRANSPARENT); //set user font to dc MyWin32.SelectObject(gxdc, this.hFont); int fontHeight = fontInfo.FontHeight; int maxLineHeight = fontHeight; for (int i = 0; i < len; ++i) { //----------------------------------------------------------------------- //measure string //and make simple character map //----------------------------------------------------------------------- //measure each character *** //not adjust kerning*** char c = buffer[i]; FontABC abcWidth = fontInfo.GetCharABCWidth(c); int glyphBoxWidth = Math.Abs(abcWidth.a) + (int)abcWidth.b + abcWidth.c; if (abcWidth.Sum + curX > this.width) { //start newline curX = 0; curY += maxLineHeight; maxLineHeight = fontHeight; } NativeTextWin32.TextOut(gxdc, curX, curY, new char[] { c }, 1); charMap.Add(c, new PixelFarm.Drawing.RectangleF(curX, curY, glyphBoxWidth, fontHeight)); curX += glyphBoxWidth; //move next } gx.ReleaseHdc(gxdc); //myTextBoardBmp = new Bitmap(width, height, new LazyGdiBitmapBufferProvider(this.textBoardBmp)); //myTextBoardBmp.InnerImage = GLBitmapTextureHelper.CreateBitmapTexture(this.textBoardBmp); }
public static bool Fill(Graphics gr, Rectangle rc, Color startColor, Color middleColor1, Color middleColor2, Color endColor, FillDirection fillDirection) { bool flag = (middleColor1 != Color.Transparent) | (middleColor2 != Color.Transparent); if (Environment.OSVersion.Platform != PlatformID.WinCE) { return FillManagedWithMiddle(gr, rc, startColor, middleColor1, middleColor2, endColor, fillDirection); } int num = 2; if (flag) { num += 2; } Win32Helper.TRIVERTEX[] pVertex = new Win32Helper.TRIVERTEX[num]; pVertex[0] = new Win32Helper.TRIVERTEX(rc.X, rc.Y, startColor); if (flag) { if (middleColor1 == Color.Transparent) { middleColor1 = middleColor2; } if (middleColor2 == Color.Transparent) { middleColor2 = middleColor1; } if (fillDirection == FillDirection.Horizontal) { pVertex[1] = new Win32Helper.TRIVERTEX(rc.X + (rc.Width / 2), rc.Bottom, middleColor1); pVertex[2] = new Win32Helper.TRIVERTEX(rc.X + (rc.Width / 2), rc.Y, middleColor2); } else { pVertex[1] = new Win32Helper.TRIVERTEX(rc.Right, rc.Y + (rc.Height / 2), middleColor1); pVertex[2] = new Win32Helper.TRIVERTEX(rc.X, rc.Y + (rc.Height / 2), middleColor2); } } pVertex[num - 1] = new Win32Helper.TRIVERTEX(rc.Right, rc.Bottom, endColor); Win32Helper.GRADIENT_RECT[] pMesh = null; if (flag) { pMesh = new Win32Helper.GRADIENT_RECT[] { new Win32Helper.GRADIENT_RECT(0, 1), new Win32Helper.GRADIENT_RECT(2, 3) }; } else { pMesh = new Win32Helper.GRADIENT_RECT[] { new Win32Helper.GRADIENT_RECT(0, 1) }; } IntPtr hdc = gr.GetHdc(); bool flag2 = false; try { flag2 = Win32Helper.GradientFill(hdc, pVertex, (uint) pVertex.Length, pMesh, (uint) pMesh.Length, (uint) fillDirection); gr.ReleaseHdc(hdc); } catch (Exception) { gr.ReleaseHdc(hdc); flag2 = FillManagedWithMiddle(gr, rc, startColor, middleColor1, middleColor2, endColor, fillDirection); } return flag2; }
/// <summary> /// Creates a new Graphics object from the device context handle associated with the Graphics /// parameter /// </summary> /// <param name="oldGraphics">Graphics instance to obtain the parameter from</param> /// <returns>A new GDI+ drawing surface</returns> public static System.Drawing.Graphics CreateGraphics(System.Drawing.Graphics oldGraphics) { System.Drawing.Graphics createdGraphics; System.IntPtr hdc = oldGraphics.GetHdc(); createdGraphics = System.Drawing.Graphics.FromHdc(hdc); oldGraphics.ReleaseHdc(hdc); return(createdGraphics); }
private void PointSymbolControl_OnDrawItem(System.Drawing.Graphics graphics, System.Drawing.RectangleF rect, int itemIndex, bool selected) { IntPtr ptr = graphics.GetHdc(); MapWinGIS.ShapeDrawingOptions sdo = _icons[itemIndex]; sdo.DrawPoint(ptr, rect.X + 1.0f, rect.Y + 1.0f, (int)rect.Width - 2, (int)rect.Height - 2, Colors.ColorToUInteger(this.BackColor)); graphics.ReleaseHdc(); }
public static void CopyGraphics(this Graphics g, Graphics gxDest, int width, int height, RasterOp op) { var srcDc = g.GetHdc(); var destDc = gxDest.GetHdc(); NativeMethods.BitBlt(destDc, 0, 0, width, height, srcDc, 0, 0, op); gxDest.ReleaseHdc(destDc); g.ReleaseHdc(srcDc); }
/// <summary> /// Wrapper around BitBlt. /// </summary> /// <param name="dest"></param> /// <param name="destClip">Clipping rectangle on dest</param> /// <param name="graphics"></param> /// <param name="bltFrom">Upper-left point on src to blt from</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">dest or graphics</exception> public static void CopyGraphics(Graphics dest, Rectangle destClip, Graphics graphics, Point bltFrom) { dest.ThrowIfNull(nameof(dest)); graphics.ThrowIfNull(nameof(graphics)); BitBlt(dest.GetHdc(), destClip.Left, destClip.Top, destClip.Width, destClip.Height, graphics.GetHdc(), bltFrom.X, bltFrom.Y, SRCCOPY); }
public static Size GetNativeResolution(IntPtr?hwnd = null) { System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(hwnd ?? IntPtr.Zero); IntPtr desktop = g.GetHdc(); int height = GetDeviceCaps(desktop, (int)DeviceCap.VERTRES); int width = GetDeviceCaps(desktop, (int)DeviceCap.HORZRES); return(new Size(width, height)); }
public static Color GetColorOfControl(System.Windows.Forms.Control control, Point point) { System.Drawing.Graphics g = control.CreateGraphics(); IntPtr dc = g.GetHdc(); Color res = ColorTranslator.FromWin32(NativeMethods.GetPixel(dc, point.X, point.Y)); NativeMethods.ReleaseDC(dc); return(res); }
IPaintTo3D IUIService.CreatePaintInterface(Bitmap paintToBitmap, double precision) { System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(paintToBitmap); PaintToOpenGL paintTo3D = new PaintToOpenGL(precision); IntPtr dc = gr.GetHdc(); paintTo3D.Init(dc, paintToBitmap.Width, paintToBitmap.Height, true); return(paintTo3D); }
private Bitmap DrawToPictureBox(ISymbol pSym, PictureBox pBox) { IPoint pPoint = null; IGeometry pGeometry = null; int hDC; System.Drawing.Graphics pGraphics = null; pGraphics = System.Drawing.Graphics.FromHwnd(pBox.Handle); //clear drawing canvas pGraphics.FillRectangle(System.Drawing.Brushes.White, pBox.ClientRectangle); if (pSym is IMarkerSymbol) { pPoint = new PointClass(); //the geometry of a MarkerSymbol pPoint.PutCoords(pBox.Width / 2, pBox.Height / 2); //center in middle of pBox pGeometry = pPoint; } if (pSym is ILineSymbol) { ISegmentCollection polyline = new ESRI.ArcGIS.Geometry.PolylineClass(); ISegment line = new ESRI.ArcGIS.Geometry.LineClass(); IPoint fromPoint = new PointClass(); fromPoint.PutCoords(pBox.Left, pBox.Bottom); IPoint toPoint = new PointClass(); toPoint.PutCoords(pBox.Right, pBox.Top); line.FromPoint = fromPoint; line.ToPoint = toPoint; object missing = Type.Missing; polyline.AddSegment(line, ref missing, ref missing); pGeometry = polyline as IGeometry; } if (pSym is IFillSymbol) { IEnvelope pEnvelope = new EnvelopeClass(); pEnvelope.PutCoords(pBox.Left, pBox.Top, pBox.Right, pBox.Bottom); pGeometry = pEnvelope; } hDC = GetDC(pBox.Handle.ToInt32()); pSym.SetupDC(hDC, null); pSym.ROP2 = esriRasterOpCode.esriROPCopyPen; pSym.Draw(pGeometry); pSym.ResetDC(); Bitmap image = new Bitmap(pBox.Width, pBox.Height, pGraphics); Graphics g2 = Graphics.FromImage(image); //获得屏幕的句柄 IntPtr dc3 = pGraphics.GetHdc(); //获得位图的句柄 IntPtr dc2 = g2.GetHdc(); BitBlt(dc2, 0, 0, pBox.Width, pBox.Height, dc3, 0, 0, SRCCOPY); pGraphics.ReleaseHdc(dc3); //释放屏幕句柄 g2.ReleaseHdc(dc2); //释放位图句柄 //image.Save("c:\\MyJpeg.Icon", ImageFormat.Bmp); return(image); }
/// <summary> /// 获得像素与长度的比例 /// </summary> /// <param name="handle"></param> /// <returns></returns> internal double GetRate(IntPtr handle) { System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(handle); IntPtr hdc = g.GetHdc(); int width = GetDeviceCaps(hdc, 4); // HORZRES int pixels = GetDeviceCaps(hdc, 8); // BITSPIXEL g.ReleaseHdc(hdc); return((double)pixels / (double)width); }
/// <summary> /// Measure a multiline string for a Control /// </summary> /// <param name="gr">Graphics</param> /// <param name="text">String to messure</param> /// <param name="rect">Original rect. The Width will be taken as fixed</param> /// <param name="textboxControl">True if you want to measure the string for a textbox control</param> /// <returns>A Size object with the measure of the string according with the params</returns> public static Size MeasureString(Graphics gr, string text, Rectangle rect, bool textboxControl) { Rect bounds = new Rect(rect); IntPtr hdc = gr.GetHdc(); int flags = DT_CALCRECT | DT_WORDBREAK; if (textboxControl) flags |= DT_EDITCONTROL; DrawText(hdc, text, text.Length, ref bounds, flags); gr.ReleaseHdc(hdc); return new Size(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top + (textboxControl ? 6 : 0)); }
public GraphicsPlus(Graphics g) { this.g = g; hdc = g.GetHdc(); GpGraphics Graphics = new GpGraphics(); lastResult = GdiPlus.GdipCreateFromHDC(hdc, out Graphics); SetNativeGraphics(Graphics); }
private float GetMainSceenUserScalingFactor() { System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero); IntPtr desktop = g.GetHdc(); int logicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.VERTRES); int physicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.DESKTOPVERTRES); float screenScalingFactor = (float)physicalScreenHeight / (float)logicalScreenHeight; return(screenScalingFactor); }
private int GetY(float p1) { System.Windows.Forms.Panel p = new System.Windows.Forms.Panel(); System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(p.Handle); IntPtr hdc = g.GetHdc(); int width = GetDeviceCaps(hdc, 90); // HORZRES g.ReleaseHdc(hdc); return((int)(p1 * 254 / width)); }
public static float getScalingFactor(IntPtr hwnd) { System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(hwnd); IntPtr desktop = g.GetHdc(); int LogicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.VERTRES); int PhysicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.DESKTOPVERTRES); float ScreenScalingFactor = (float)PhysicalScreenHeight / (float)LogicalScreenHeight; return(ScreenScalingFactor); // 1.25 = 125% }
public static int MMToPixels(int length) { System.Windows.Forms.Panel p = new System.Windows.Forms.Panel(); System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(p.Handle); IntPtr hdc = g.GetHdc(); int width = GetDeviceCaps(hdc, 4); // HORZRES int pixels = GetDeviceCaps(hdc, 8); // BITSPIXEL g.ReleaseHdc(hdc); return((pixels / width) * length); }
public static double MillimetersToPixelsWidth(double length) //length是毫米,1厘米=10毫米 { System.Windows.Forms.Panel p = new System.Windows.Forms.Panel(); System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(p.Handle); IntPtr hdc = g.GetHdc(); int width = GetDeviceCaps(hdc, 4); // HORZRES int pixels = GetDeviceCaps(hdc, 8); // BITSPIXEL g.ReleaseHdc(hdc); return(((double)pixels / (double)width) * (double)length); }
protected virtual void HandlePrintPage(object sender, sdp.PrintPageEventArgs e) { using (var graphics = e.Graphics.ToEto(false)) { var bounds = e.MarginBounds; var container = _control.GetContainerControl(); if (container != null) { container.SuspendLayout(); container.Width = (int)Math.Max(bounds.Width, _preferredSize.Width); container.Height = (int)Math.Max(bounds.Height, _preferredSize.Height); container.ResumeLayout(); // create an offscreen bitmap to paint to var bitmapSize = bounds.Size; if (_controlBitmap == null || _controlBitmap.Size != bitmapSize) { _controlBitmap?.Dispose(); _controlBitmap = new sd.Bitmap(bitmapSize.Width, bitmapSize.Height, sd.Imaging.PixelFormat.Format32bppArgb); } // setup a graphics object to paint to sd.Graphics g = sd.Graphics.FromImage(_controlBitmap); var hdc = g.GetHdc(); // set the offset for the current page var y = _currentPage * bounds.Height; var oldOffset = new Win32.POINT(); Win32.OffsetWindowOrgEx(hdc, 0, y, ref oldOffset); // send the WM_PRINT message Win32.SendMessage( container.Handle, Win32.WM.PRINT, hdc, (IntPtr)(Win32.PRF.CHILDREN | Win32.PRF.CLIENT | Win32.PRF.ERASEBKGND | Win32.PRF.NONCLIENT)); // restore offset Win32.OffsetWindowOrgEx(hdc, oldOffset.x, oldOffset.y, ref oldOffset); g.ReleaseHdc(hdc); g.Dispose(); // draw the image to the print graphics context e.Graphics.DrawImage(_controlBitmap, bounds); } graphics.TranslateTransform(bounds.Left, bounds.Top); var args = new PrintPageEventArgs(graphics, bounds.Size.ToEto(), _currentPage); Callback.OnPrintPage(Widget, args); _currentPage++; e.HasMorePages = _currentPage < PageCount; } }
public static void DrawText(Graphics graphics, string text, Font font, Rectangle bounds, Color color, TextFormatFlags flags, TextStyle textStyle) { if (!VisualStyleRenderer.IsSupported) { TextRenderer.DrawText(graphics, text, font, bounds, color, flags); return; } IntPtr primaryHdc = graphics.GetHdc(); // Create a memory DC so we can work offscreen IntPtr memoryHdc = CreateCompatibleDC(primaryHdc); // Create a device-independent bitmap and select it into our DC BITMAPINFO info = new BITMAPINFO(); info.biSize = Marshal.SizeOf(info); info.biWidth = bounds.Width; info.biHeight = -bounds.Height; info.biPlanes = 1; info.biBitCount = 32; info.biCompression = 0; // BI_RGB IntPtr dib = CreateDIBSection(primaryHdc, info, 0, 0, IntPtr.Zero, 0); SelectObject(memoryHdc, dib); // Create and select font IntPtr fontHandle = font.ToHfont(); SelectObject(memoryHdc, fontHandle); // Draw glowing text VisualStyleRenderer renderer = new VisualStyleRenderer(System.Windows.Forms.VisualStyles.VisualStyleElement.Window.Caption.Active); DTTOPTS dttOpts = new DTTOPTS(); dttOpts.dwSize = Marshal.SizeOf(typeof(DTTOPTS)); if (textStyle == TextStyle.Glowing) { dttOpts.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE | DTT_TEXTCOLOR; } else { dttOpts.dwFlags = DTT_COMPOSITED | DTT_TEXTCOLOR; } dttOpts.crText = ColorTranslator.ToWin32(color); dttOpts.iGlowSize = 8; // This is about the size Microsoft Word 2007 uses RECT textBounds = new RECT(0, 0, bounds.Right - bounds.Left, bounds.Bottom - bounds.Top); DrawThemeTextEx(renderer.Handle, memoryHdc, 0, 0, text, -1, (int)flags, ref textBounds, ref dttOpts); // Copy to foreground const int SRCCOPY = 0x00CC0020; BitBlt(primaryHdc, bounds.Left, bounds.Top, bounds.Width, bounds.Height, memoryHdc, 0, 0, SRCCOPY); // Clean up DeleteObject(fontHandle); DeleteObject(dib); DeleteDC(memoryHdc); graphics.ReleaseHdc(primaryHdc); }
/// <summary> /// Measure a multiline string /// </summary> /// <param name="gr">Graphics</param> /// <param name="text">string to measure</param> /// <param name="rect">Original rect. The width will be taken as fixed.</param> /// <param name="textboxControl">True if you want to measure the string for a textbox control</param> /// <returns>A Size object with the measure of the string according with the params</returns> public static Size GetBestSize(Graphics gr, string text, Rectangle rect, bool textboxControl) { NativeMethods.RECT bounds = new NativeMethods.RECT(rect); IntPtr hdc = gr.GetHdc(); int flags = NativeMethods.DT_CALCRECT | NativeMethods.DT_WORDBREAK; if (textboxControl) flags |= NativeMethods.DT_EDITCONTROL; NativeMethods.DrawText(hdc, text, text.Length, ref bounds, flags); gr.ReleaseHdc(hdc); return new Size(bounds.right - bounds.left, bounds.bottom - bounds.top + (textboxControl ? 6 : 0)); }
public static int MillimetersToPixelsWidth(decimal length) { System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(new Form().Handle); IntPtr hdc = g.GetHdc(); int width = GetDeviceCaps(hdc, 4); int pixels = GetDeviceCaps(hdc, 8); g.ReleaseHdc(hdc); return((int)(((double)pixels / (double)width) * (double)length)); }
public static double MillimetersToPixelsWidthX(double length, Graphics g1) { System.Windows.Forms.Panel p = new System.Windows.Forms.Panel(); System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(p.Handle); IntPtr hdc = g.GetHdc(); int width = GetDeviceCaps(hdc, 88); // HORZRES //int pixels = GetDeviceCaps(hdc, 88); // BITSPIXEL g.ReleaseHdc(hdc); //return (((double)pixels / (double)width) * (double)length) / 25.4; return(width * length / 254); }