/// <summary> /// 获取RGB颜色 /// </summary> /// <param name="r">红色值</param> /// <param name="g">绿色值</param> /// <param name="b">蓝色值</param> /// <returns>RGB颜色</returns> public static int RGB(int r, int g, int b) { return(ColorTranslator.ToWin32(Color.FromArgb(r, g, b))); }
private void FloodFill1(int x0, int y0) { int savex, xleft, xright, pflag, x, y, num; Point[] stack_ptr = new Point[200]; Graphics g = CreateGraphics(); IntPtr hdc = g.GetHdc(); IntPtr hpen = CreatePen(0, 1, ColorTranslator.ToWin32(Color.Red)); SetROP2(hdc, 13); IntPtr pOldPen = SelectObject(hdc, hpen); num = 0; stack_ptr[num++] = new Point(x0, y0); while (num > 0) { x = stack_ptr[--num].X; y = stack_ptr[num].Y; SetPixel(hdc, x, y, ColorTranslator.ToWin32(Color.Red)); savex = x; x++; while (GetPixel(hdc, x, y) != ColorTranslator.ToWin32(Color.Red)) { SetPixel(hdc, x++, y, ColorTranslator.ToWin32(Color.Red)); } xright = x - 1; x = savex - 1; while (GetPixel(hdc, x, y) != ColorTranslator.ToWin32(Color.Red)) { SetPixel(hdc, x--, y, ColorTranslator.ToWin32(Color.Red)); } xleft = x + 1; x = xleft; y++; pflag = 1; while (x < xright) { if (GetPixel(hdc, x, y) != ColorTranslator.ToWin32(Color.Red) && pflag == 1) { stack_ptr[num].X = x; stack_ptr[num++].Y = y; x++; } if (GetPixel(hdc, x, y) == ColorTranslator.ToWin32(Color.Red)) { pflag = 1; } else { pflag = 0; } x++; } x = xleft; y -= 2; pflag = 1; while (x < xright) { if (GetPixel(hdc, x, y) != ColorTranslator.ToWin32(Color.Red) && pflag == 1) { stack_ptr[num].X = x; stack_ptr[num++].Y = y; x++; } if (GetPixel(hdc, x, y) == ColorTranslator.ToWin32(Color.Red)) { pflag = 1; } else { pflag = 0; } x++; } } SelectObject(hdc, pOldPen); g.ReleaseHdc(hdc); }
private void CreatePen() { if (this.width > 1) // Geometric pen. { // From MSDN: if width > 1, the style must be PS_NULL, PS_SOLID, or PS_INSIDEFRAME. this.style |= WindowsPenStyle.Geometric | WindowsPenStyle.Solid; } if (this.wndBrush == null) { this.nativeHandle = IntSafeNativeMethods.CreatePen((int)this.style, this.width, ColorTranslator.ToWin32(this.color)); } else { IntNativeMethods.LOGBRUSH lb = new IntNativeMethods.LOGBRUSH(); lb.lbColor = ColorTranslator.ToWin32(this.wndBrush.Color); lb.lbStyle = IntNativeMethods.BS_SOLID; lb.lbHatch = 0; // Note: We currently don't support custom styles, that's why 0 and null for last two params. this.nativeHandle = IntSafeNativeMethods.ExtCreatePen((int)this.style, this.width, lb, 0, null); } }
/// <devdoc> /// Sets the DC background color and returns the old value. /// </devdoc> public Color SetBackgroundColor(Color newColor) { return(ColorTranslator.FromWin32(IntUnsafeNativeMethods.SetBkColor(new HandleRef(this, this.Hdc), ColorTranslator.ToWin32(newColor)))); }
/// <summary> /// Handles the DrawItem event of the LB control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="DrawItemEventArgs"/> instance containing the event data.</param> private void LB_DrawItem(object sender, DrawItemEventArgs e) { bool selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected; if (e.Index == -1) { return; } object li = FontListbox.Items[e.Index]; string text = li.ToString(); Brush bg, fg; if (selected) { bg = SystemBrushes.Highlight; fg = SystemBrushes.HighlightText; //fg=Brushes.Black; } else { bg = SystemBrushes.Window; fg = SystemBrushes.WindowText; } //e.Graphics.FillRectangle (SystemBrushes.Window,0,e.Bounds.Top,e.Bounds.Width ,FontListbox.ItemHeight); if (selected) { int ofs = 37; e.Graphics.FillRectangle(SystemBrushes.Window, new Rectangle(ofs, e.Bounds.Top, e.Bounds.Width - ofs, FontListbox.ItemHeight)); e.Graphics.FillRectangle(SystemBrushes.Highlight, new Rectangle(ofs + 1, e.Bounds.Top + 1, e.Bounds.Width - ofs - 2, FontListbox.ItemHeight - 2)); System.Windows.Forms.ControlPaint.DrawFocusRectangle(e.Graphics, new Rectangle(ofs, e.Bounds.Top, e.Bounds.Width - ofs, FontListbox.ItemHeight)); } else { e.Graphics.FillRectangle(SystemBrushes.Window, 0, e.Bounds.Top, e.Bounds.Width, FontListbox.ItemHeight); } e.Graphics.DrawString(text, e.Font, fg, 38, e.Bounds.Top + 4); e.Graphics.SetClip(new Rectangle(1, e.Bounds.Top + 2, 34, FontListbox.ItemHeight - 4)); e.Graphics.FillRectangle(SystemBrushes.Highlight, new Rectangle(1, e.Bounds.Top + 2, 34, FontListbox.ItemHeight - 4)); IntPtr hdc = e.Graphics.GetHdc(); GDIFont gf = new GDIFont(text, 9); int a = 0; IntPtr res = NativeGdi32Api.SelectObject(hdc, gf.hFont); NativeGdi32Api.SetTextColor(hdc, ColorTranslator.ToWin32(SystemColors.Window)); NativeGdi32Api.SetBkMode(hdc, 0); NativeUser32Api.TabbedTextOut(hdc, 3, e.Bounds.Top + 5, "abc", 3, 0, ref a, 0); NativeGdi32Api.SelectObject(hdc, res); gf.Dispose(); e.Graphics.ReleaseHdc(hdc); e.Graphics.DrawRectangle(Pens.Black, new Rectangle(1, e.Bounds.Top + 2, 34, FontListbox.ItemHeight - 4)); e.Graphics.ResetClip(); }
public static string ToWin32(Color _c) { return(ColorTranslator.ToWin32(_c).ToString()); }
internal static void DrawTextInternal(IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor, Color backColor, TextFormatFlags flags, bool useDrawString) { if (dc == null) { throw new ArgumentNullException("dc"); } if ((text == null || text.Length == 0) && (backColor == Color.Transparent || backColor == Color.Empty)) { return; } // We use MS GDI API's unless told not to, or we aren't on Windows if (!useDrawString && !XplatUI.RunningOnUnix) { if ((flags & TextFormatFlags.VerticalCenter) == TextFormatFlags.VerticalCenter || (flags & TextFormatFlags.Bottom) == TextFormatFlags.Bottom) { flags |= TextFormatFlags.SingleLine; } // Calculate the text bounds (there is often padding added) Rectangle new_bounds = PadRectangle(bounds, flags); new_bounds.Offset((int)(dc as Graphics).Transform.OffsetX, (int)(dc as Graphics).Transform.OffsetY); IntPtr hdc = IntPtr.Zero; bool clear_clip_region = false; // If we need to use the graphics clipping region, add it to our hdc if ((flags & TextFormatFlags.PreserveGraphicsClipping) == TextFormatFlags.PreserveGraphicsClipping) { Graphics graphics = (Graphics)dc; Region clip_region = graphics.Clip; if (!clip_region.IsInfinite(graphics)) { IntPtr hrgn = clip_region.GetHrgn(graphics); hdc = dc.GetHdc(); SelectClipRgn(hdc, hrgn); DeleteObject(hrgn); clear_clip_region = true; } } if (hdc == IntPtr.Zero) { hdc = dc.GetHdc(); } // Set the fore color if (foreColor != Color.Empty) { SetTextColor(hdc, ColorTranslator.ToWin32(foreColor)); } // Set the back color if (backColor != Color.Transparent && backColor != Color.Empty) { SetBkMode(hdc, 2); //1-Transparent, 2-Opaque SetBkColor(hdc, ColorTranslator.ToWin32(backColor)); } else { SetBkMode(hdc, 1); //1-Transparent, 2-Opaque } XplatUIWin32.RECT r = XplatUIWin32.RECT.FromRectangle(new_bounds); IntPtr prevobj; if (text == null || text.Length == 0) { Win32DrawText(hdc, String.Empty, 0, ref r, (int)flags); } else if (font != null) { prevobj = SelectObject(hdc, font.ToHfont()); Win32DrawText(hdc, text, text.Length, ref r, (int)flags); prevobj = SelectObject(hdc, prevobj); DeleteObject(prevobj); } else { Win32DrawText(hdc, text, text.Length, ref r, (int)flags); } if (clear_clip_region) { SelectClipRgn(hdc, IntPtr.Zero); } dc.ReleaseHdc(); } // Use Graphics.DrawString as a fallback method else { Graphics g; IntPtr hdc = IntPtr.Zero; if (dc is Graphics) { g = (Graphics)dc; } else { hdc = dc.GetHdc(); g = Graphics.FromHdc(hdc); } if (backColor != Color.Transparent && backColor != Color.Empty) { using (SolidBrush b = new SolidBrush(backColor)) g.FillRectangle(b, bounds); } if (text != null && text.Length > 0) { StringFormat sf = FlagsToStringFormat(flags); // It seems that Win32 TextRenderer behaves likes this if ((flags & TextFormatFlags.WordBreak) == 0 && (flags & TextFormatFlags.TextBoxControl) == 0) { sf.FormatFlags |= StringFormatFlags.NoWrap; } Rectangle new_bounds = PadDrawStringRectangle(bounds, flags); g.DrawString(text, font, ThemeEngine.Current.ResPool.GetSolidBrush(foreColor), new_bounds, sf); } if (!(dc is Graphics)) { g.Dispose(); dc.ReleaseHdc(); } } }
internal override void Apply(ref NativeMethods.DTTOPTS options) { options.dwFlags |= NativeMethods.DTTOPSFlags.DTT_BORDERCOLOR | NativeMethods.DTTOPSFlags.DTT_BORDERSIZE; options.crBorder = ColorTranslator.ToWin32(BorderColor); options.iBorderSize = BorderSize; }
public static bool ScriptTextOut(string filePathSave, System.Drawing.Font font, List <int> xArray, List <int> yArray, uint fuOptions, Win32.RECT lprc, List <Uniscribe.SCRIPT_ANALYSIS> psaArray, string pwcReserved, int iReserved, List <ushort[]> pwGlyphsArray, List <int> cGlyphsArray, List <int[]> piAdvanceArray, List <int[]> piJustifyArray, List <Uniscribe.GOFFSET[]> pGoffsetArray) { bool res = false; int width = 500; int height = 400; System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, width, height); lprc = new Win32.RECT(rect); Bitmap bitmap = null; Graphics gr = null; IntPtr HDC = IntPtr.Zero; createBitmap(font, ref bitmap, width, height, ref gr); HDC = gr.GetHdc(); // HFONT hfont = initialize your font; IntPtr hfont = font.ToHfont(); // HFONT old_font = NULL; IntPtr old_font = IntPtr.Zero; // ... select font into hdc ... old_font = Win32.SelectObject(HDC, hfont); int old_color = 0; old_color = Win32.SetTextColor(HDC, ColorTranslator.ToWin32(System.Drawing.Color.Black)); System.Drawing.Color color = ColorTranslator.FromWin32(old_color); old_color = Win32.SetBkColor(HDC, ColorTranslator.ToWin32(System.Drawing.Color.Yellow)); color = ColorTranslator.FromWin32(old_color); string text = "It's me!"; Win32.RECT bounds = new Win32.RECT(rect); int flags = Win32.DT_CENTER | Win32.DT_VCENTER | Win32.DT_SINGLELINE; uint result = 0; result = Win32.DrawText(HDC, text, text.Length, ref bounds, flags); IntPtr psc = IntPtr.Zero; // Initialize to NULL, will be filled lazily. for (int i = 0; i < psaArray.Count; i++) { res = callScriptTextOutForItem(HDC, psc, xArray[i], yArray[i], fuOptions, lprc, psaArray[i], pwcReserved, iReserved, pwGlyphsArray[i], cGlyphsArray[i], piAdvanceArray[i], piJustifyArray[i], pGoffsetArray[i]); if (!res) { } } if (old_font != IntPtr.Zero) { Win32.SelectObject(HDC, old_font); // Put back the previous font. } gr.ReleaseHdc(HDC); saveBitmap(bitmap, gr, filePathSave); return(res); }
/// <summary> /// Sets the DC text color and returns the old value. /// </summary> public Color SetTextColor(Color newColor) { return(ColorTranslator.FromWin32(IntUnsafeNativeMethods.SetTextColor(new HandleRef(this, Hdc), ColorTranslator.ToWin32(newColor)))); }
public void ExportExcel(DataGridView dgv, string rptName, int inFirstRow, int inFirstCol, string Format, object dtFromDate, object dtToDate, string header)//, string credit, string debit, string closing) { try { if (CheckWhetherOfficeInstalled()) { int inColN = 1; Cursor.Current = Cursors.WaitCursor; string strName = "", strAddress = "", strPhone = ""; Excel.Range range = null; Excel.Application excel = new Excel.Application(); Excel.Workbook wb = excel.Workbooks.Add(Excel.XlSheetType.xlWorksheet); Excel.Worksheet ws = (Excel.Worksheet)excel.ActiveSheet; CompanySP spCompany = new CompanySP(); DataTable dtblCompany = spCompany.CompanyViewDataTable(1); //BranchInfo InfoBranch = new BranchInfo(); //BranchSP SpBranch = new BranchSP(); // InfoBranch = SpBranch.BranchView(PublicVariables._branchId); strAddress = dtblCompany.Rows[0].ItemArray[3].ToString().Replace("\r\n", " "); strPhone = dtblCompany.Rows[0].ItemArray[4].ToString(); strName = dtblCompany.Rows[0].ItemArray[1].ToString(); //BranchInfo InfoBranch = new BranchInfo(); //BranchSP SpBranch = new BranchSP(); //InfoBranch = SpBranch.BranchView(PublicVariables._branchId); //strAddress = InfoBranch.Address.Replace("\r\n", " "); //if (InfoBranch.PhoneNo == "") //{ // strPhone = InfoBranch.Mobile; //} //else //{ // strPhone = InfoBranch.PhoneNo; //} //strName = InfoBranch.BranchName; //**************Report Header *************************************** //range = (Excel.Range)ws.Cells[1, 1]; range = ws.get_Range("A1", "I1"); range.MergeCells = true; range.Font.Size = 15; range.RowHeight = 27; range.Interior.Color = ColorTranslator.ToWin32(Color.LightGray); range.Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; range.Cells.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; range.Value2 = strName; range = ws.get_Range("A2", "I2"); range.MergeCells = true; range.Font.Size = 10; range.Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; range.Value2 = strAddress; range = ws.get_Range("A3", "I3"); range.MergeCells = true; range.Font.Size = 10; range.Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; range.Value2 = "Phone No :" + strPhone; range = ws.get_Range("A5", "G5"); range.MergeCells = true; range.Font.Size = 11; range.Value2 = rptName; range.Font.Underline = true; range.Font.Bold = true; range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; range = ws.get_Range("A6", "G6"); range.MergeCells = true; //range.Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; range.Font.Size = 11; if (dtFromDate != null && dtToDate != null) { range.Value2 = "(" + DateTime.Parse(dtFromDate.ToString()).Date.ToString("dd-MMM-yyyy") + " To " + DateTime.Parse(dtToDate.ToString()).Date.ToString("dd-MMM-yyyy") + ")"; } else if (dtFromDate != null) { range.Value2 = DateTime.Parse(dtFromDate.ToString()).Date.ToString("dd-MMM-yyyy"); } range.Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; range.MergeCells = true; range.Font.Bold = true; range = ws.get_Range("H5", "H5"); range.Value2 = "Date :"; range.Font.Bold = true; range = ws.get_Range("I5", "I5"); range.Value2 = PublicVariables._dtCurrentDate.Date.ToString("dd-MMM-yyyy"); range.Font.Bold = true; int inNewRow = 0; inNewRow = inFirstRow; for (int inRow = inFirstRow; inRow < dgv.Rows.Count; inRow++) { if (dgv.Rows[inRow].Visible != false) { for (int inCol = inFirstCol; inCol < dgv.Columns.Count; inCol++) { if (inRow == 0) { if (dgv.Columns[inCol].Visible == true) { range = (Excel.Range)ws.Cells[inNewRow + 8, inColN]; range.Font.Bold = true; range.Interior.Color = ColorTranslator.ToWin32(Color.LightGray); range.Value2 = dgv.Columns[inCol].HeaderText; } } range = (Excel.Range)ws.Cells[inNewRow + 9, inColN]; if (dgv[inCol, inRow].Style.Font != null) { if (dgv[inCol, inRow].Style.Font.Bold) { range.Font.Bold = true; } } if (dgv.Rows[inRow].DefaultCellStyle.BackColor == Color.LightSkyBlue) { range.Font.Bold = true; range.Interior.Color = ColorTranslator.ToWin32(Color.LightGray); } if (dgv.Rows[inRow].DefaultCellStyle.ForeColor == Color.Red) { range.Font.Bold = true; range.Interior.Color = ColorTranslator.ToWin32(Color.LightGray); } //if (dgv.Rows[inRow].Visible != false) //{ if (dgv.Columns[inCol].Visible == true) { range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlHairline, Excel.XlColorIndex.xlColorIndexAutomatic, 1); if (dgv[inCol, inRow].Value != null) { string str = dgv[inCol, inRow].Value.ToString(); try { if (dgv.Columns[inCol].HeaderText.Replace(" ", "").ToLower() == "phoneno" || dgv.Columns[inCol].HeaderText.Replace(" ", "").ToLower() == "phonenumber") { range.NumberFormat = "@"; } else { decimal.Parse(str); decimal dc = Math.Round(decimal.Parse(str), 2); str = dc.ToString(); if (dgv.Columns[inCol].Name.ToLower() == "debit" || dgv.Columns[inCol].Name.ToLower() == "credit") { range.NumberFormat = "#00.00#"; } else { range.NumberFormat = "General"; } } } catch (Exception) { try { DateTime.Parse(str); range.NumberFormat = "dd-MMM-yyyy"; range.NumberFormat = "General"; } catch (Exception) { range.NumberFormat = "@"; } } if (str.Contains("Dr") || str.Contains("Cr")) { range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight; } //try //{ // if (dgv.Columns[inCol].HeaderText.Replace(" ", "").ToLower() == "phoneno" || dgv.Columns[inCol].HeaderText.Replace(" ", "").ToLower() == "phonenumber") // range.NumberFormat = "@"; // else // { // decimal.Parse(str); // decimal dc = Math.Round(decimal.Parse(str), 2); // str = dc.ToString(); // } //} //catch (Exception) //{ // try // { // DateTime.Parse(str); // range.NumberFormat = "dd-MMM-yyyy"; // range.NumberFormat = "General"; // } // catch (Exception) // { // //range.NumberFormat = "@"; // range.NumberFormat = "General"; // } //} //------------------------------------ //------------------------------------ range.Value2 = str;// dgv[inCol, inRow].Value; } inColN++; } //} } inColN = 1; inNewRow++; } } inNewRow = inNewRow + 10; ws.Columns.AutoFit(); if (Format == "Excel") { excel.Visible = true; } //else if (Format == "Html") //{ // //***********Deleting all format************* // ws.Columns.AutoFit(); // FileInfo infoHtml = new FileInfo(Application.StartupPath + "\\Report.html"); // if (infoHtml.Exists) // { // infoHtml.Delete(); // } // //******************************************* // ws.SaveAs(Application.StartupPath + "\\Report.html", Excel.XlFileFormat.xlHtml, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value); // excel.Quit(); // System.Diagnostics.Process.Start("IExplore.exe", Application.StartupPath + "\\Report.html"); //} Cursor.Current = Cursors.Default; } else { MessageBox.Show("Install office", "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
/// <summary> /// Gets the name of the color. /// </summary> /// <param name="c">The c.</param> /// <returns>System.String.</returns> public string GetColorName(Color c) { foreach (string ColorName in Known_Color) { if (!(Color.FromName(ColorName).IsSystemColor)) { if (Convert.ToInt32(ColorTranslator.ToWin32(Color.FromName(ColorName))) == Convert.ToInt32(ColorTranslator.ToWin32(c))) { return(((c.Name == "ffffffff") ? "White- ffffffff" : ColorName + "- " + c.Name).ToString()); } } } return(((c.Name == "ff7f007f") ? "Transparent- ff7f007f" : c.Name).ToString()); }
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); IntPtr prevDib = SelectObject(memoryHdc, dib); // Create and select font IntPtr fontHandle = font.ToHfont(); IntPtr prevFont = 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(prevFont); DeleteObject(dib); DeleteObject(prevDib); DeleteDC(memoryHdc); graphics.ReleaseHdc(primaryHdc); }
/// <summary> /// 获取RGB颜色 /// </summary> /// <param name="r">红色值</param> /// <returns>RGB颜色</returns> public static int RGB(Color cl) { return(ColorTranslator.ToWin32(cl)); }
public string ToRawSsa(string styleFormat) { var sb = new StringBuilder(); sb.Append("Style: "); var format = styleFormat.ToLowerInvariant().Substring(8).Split(','); for (int i = 0; i < format.Length; i++) { string f = format[i].Trim(); if (f == "name") { sb.Append(Name); } else if (f == "fontname") { sb.Append(FontName); } else if (f == "fontsize") { sb.Append(FontSize); } else if (f == "primarycolour") { sb.Append(ColorTranslator.ToWin32(Primary)); } else if (f == "secondarycolour") { sb.Append(ColorTranslator.ToWin32(Secondary)); } else if (f == "tertiarycolour") { sb.Append(ColorTranslator.ToWin32(Tertiary)); } else if (f == "outlinecolour") { sb.Append(ColorTranslator.ToWin32(Outline)); } else if (f == "backcolour") { sb.Append(ColorTranslator.ToWin32(Background)); } else if (f == "bold") { sb.Append(Convert.ToInt32(Bold)); } else if (f == "italic") { sb.Append(Convert.ToInt32(Italic)); } else if (f == "underline") { sb.Append(Convert.ToInt32(Underline)); } else if (f == "outline") { sb.Append(Outline); } else if (f == "shadow") { sb.Append(OutlineWidth); } else if (f == "marginl") { sb.Append(MarginLeft); } else if (f == "marginr") { sb.Append(MarginRight); } else if (f == "marginv") { sb.Append(MarginVertical); } else if (f == "borderstyle") { sb.Append(BorderStyle); } else if (f == "encoding") { sb.Append('1'); } else if (f == "strikeout") { sb.Append('0'); } else if (f == "scalex") { sb.Append("100"); } else if (f == "scaley") { sb.Append("100"); } else if (f == "spacing") { sb.Append('0'); } else if (f == "angle") { sb.Append('0'); } sb.Append(','); } string s = sb.ToString().Trim(); return(s.Substring(0, s.Length - 1)); }
protected override void OnForeColorChanged(EventArgs e) { base.OnForeColorChanged(e); if (IsHandleCreated) { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBARCOLOR, 0, ColorTranslator.ToWin32(ForeColor)); } }
private void DrawDottedGrip( Graphics graphics, Rectangle bounds, bool vertical, bool largeDot, Color innerColor, Color outerColor) { bounds.Height -= 3; Point position = new Point(bounds.X, bounds.Y); int sep; Rectangle posRect = new Rectangle(0, 0, 2, 2); using (SmoothingModeGraphics sg = new SmoothingModeGraphics(graphics)) { IntPtr hdc; if (vertical) { sep = bounds.Height; position.Y += 8; for (int i = 0; position.Y > 4; i += 4) { position.Y = sep - (2 + i); if (largeDot) { posRect.Location = position; DrawCircle( graphics, posRect, outerColor, innerColor); } else { int innerWin32Corlor = ColorTranslator.ToWin32(innerColor); int outerWin32Corlor = ColorTranslator.ToWin32(outerColor); hdc = graphics.GetHdc(); SetPixel( hdc, position.X, position.Y, innerWin32Corlor); SetPixel( hdc, position.X + 1, position.Y, outerWin32Corlor); SetPixel( hdc, position.X, position.Y + 1, outerWin32Corlor); SetPixel( hdc, position.X + 3, position.Y, innerWin32Corlor); SetPixel( hdc, position.X + 4, position.Y, outerWin32Corlor); SetPixel( hdc, position.X + 3, position.Y + 1, outerWin32Corlor); graphics.ReleaseHdc(hdc); } } } else { bounds.Inflate(-2, 0); sep = bounds.Width; position.X += 2; for (int i = 1; position.X > 0; i += 4) { position.X = sep - (2 + i); if (largeDot) { posRect.Location = position; DrawCircle(graphics, posRect, outerColor, innerColor); } else { int innerWin32Corlor = ColorTranslator.ToWin32(innerColor); int outerWin32Corlor = ColorTranslator.ToWin32(outerColor); hdc = graphics.GetHdc(); SetPixel( hdc, position.X, position.Y, innerWin32Corlor); SetPixel( hdc, position.X + 1, position.Y, outerWin32Corlor); SetPixel( hdc, position.X, position.Y + 1, outerWin32Corlor); SetPixel( hdc, position.X + 3, position.Y, innerWin32Corlor); SetPixel( hdc, position.X + 4, position.Y, outerWin32Corlor); SetPixel( hdc, position.X + 3, position.Y + 1, outerWin32Corlor); graphics.ReleaseHdc(hdc); } } } } }
/// <include file='doc\ProgressBar.uex' path='docs/doc[@for="ProgressBar.OnHandleCreated"]/*' /> /// <devdoc> /// Overridden to set up our properties. /// </devdoc> /// <internalonly/> protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); SendMessage(NativeMethods.PBM_SETRANGE32, minimum, maximum); SendMessage(NativeMethods.PBM_SETSTEP, step, 0); SendMessage(NativeMethods.PBM_SETPOS, value, 0); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBKCOLOR, 0, ColorTranslator.ToWin32(BackColor)); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBARCOLOR, 0, ColorTranslator.ToWin32(ForeColor)); StartMarquee(); SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(UserPreferenceChangedHandler); }
public void ToWin32Color_Color_ReturnsExpected(Color color, int expected) { Assert.Equal(expected, ColorTranslator.ToWin32(color)); }
//Note: ProgressBar doesn't work like other controls as far as setting ForeColor/ //BackColor -- you need to send messages to update the colors private void UserPreferenceChangedHandler(object o, UserPreferenceChangedEventArgs e) { if (IsHandleCreated) { UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBARCOLOR, 0, ColorTranslator.ToWin32(ForeColor)); UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.PBM_SETBKCOLOR, 0, ColorTranslator.ToWin32(BackColor)); } }
static public void SetIndicatorStyle(this ScintillaGateway document, int indicator, SciMsg style, Color color) { document.IndicSetStyle(indicator, (int)style); document.IndicSetFore(indicator, new Colour(ColorTranslator.ToWin32(color))); }
private void PaintThis(IntPtr hdc, RECT rc) { RECT clientRect = new RECT(); GetClientRect(this.Handle, ref clientRect); if (_bExtendIntoFrame) { clientRect.Left = _tClientRect.Left - _tMargins.cxLeftWidth; clientRect.Top = _tMargins.cyTopHeight; clientRect.Right -= _tMargins.cxRightWidth; clientRect.Bottom -= _tMargins.cyBottomHeight; } else if (!_bPaintWindow) { clientRect.Left = _tMargins.cxLeftWidth; clientRect.Top = _tMargins.cyTopHeight; clientRect.Right -= _tMargins.cxRightWidth; clientRect.Bottom -= _tMargins.cyBottomHeight; } if (!_bPaintWindow) { int clr; IntPtr hb; using (ClippingRegion cp = new ClippingRegion(hdc, clientRect, rc)) { if (IsAero()) { FillRect(hdc, ref rc, GetStockObject(BLACK_BRUSH)); } else { clr = ColorTranslator.ToWin32(Color.FromArgb(0xC2, 0xD9, 0xF7)); hb = CreateSolidBrush(clr); FillRect(hdc, ref clientRect, hb); DeleteObject(hb); } } clr = ColorTranslator.ToWin32(this.BackColor); hb = CreateSolidBrush(clr); FillRect(hdc, ref clientRect, hb); DeleteObject(hb); } else { FillRect(hdc, ref rc, GetStockObject(BLACK_BRUSH)); } if (_bExtendIntoFrame && _bDrawCaption) { Rectangle captionBounds = new Rectangle(4, 4, rc.Right, CaptionHeight); using (Graphics g = Graphics.FromHdc(hdc)) { using (Font fc = new Font("Segoe UI", 12, FontStyle.Regular)) { SizeF sz = g.MeasureString(this.Text, fc); int offset = (rc.Right - (int)sz.Width) / 2; if (offset < 2 * FrameWidth) { offset = 2 * FrameWidth; } captionBounds.X = offset; captionBounds.Y = 4; using (StringFormat sf = new StringFormat()) { sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None; sf.FormatFlags = StringFormatFlags.NoWrap; sf.Alignment = StringAlignment.Near; sf.LineAlignment = StringAlignment.Near; using (GraphicsPath path = new GraphicsPath()) { g.SmoothingMode = SmoothingMode.HighQuality; path.AddString(this.Text, fc.FontFamily, (int)fc.Style, fc.Size, captionBounds, sf); g.FillPath(Brushes.Black, path); } } } } } }
/// <include file='doc\FontDialog.uex' path='docs/doc[@for="FontDialog.RunDialog"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// The actual implementation of running the dialog. Inheriting classes /// should override this if they want to add more functionality, and call /// base.runDialog() if necessary /// /// </para> /// </devdoc> protected override bool RunDialog(IntPtr hWndOwner) { NativeMethods.WndProc hookProcPtr = new NativeMethods.WndProc(this.HookProc); NativeMethods.CHOOSEFONT cf = new NativeMethods.CHOOSEFONT(); IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); NativeMethods.LOGFONT lf = new NativeMethods.LOGFONT(); Graphics graphics = Graphics.FromHdcInternal(screenDC); try { Font.ToLogFont(lf, graphics); } finally { graphics.Dispose(); } UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); IntPtr logFontPtr = IntPtr.Zero; try { logFontPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(NativeMethods.LOGFONT))); Marshal.StructureToPtr(lf, logFontPtr, false); cf.lStructSize = Marshal.SizeOf(typeof(NativeMethods.CHOOSEFONT)); cf.hwndOwner = hWndOwner; cf.hDC = IntPtr.Zero; cf.lpLogFont = logFontPtr; cf.Flags = Options | NativeMethods.CF_INITTOLOGFONTSTRUCT | NativeMethods.CF_ENABLEHOOK; if (minSize > 0 || maxSize > 0) { cf.Flags |= NativeMethods.CF_LIMITSIZE; } //if ShowColor=true then try to draw the sample text in color, //if ShowEffects=false then we will draw the sample text in standard control text color regardless. //(limitation of windows control) // if (ShowColor || ShowEffects) { cf.rgbColors = ColorTranslator.ToWin32(color); } else { cf.rgbColors = ColorTranslator.ToWin32(SystemColors.ControlText); } cf.lpfnHook = hookProcPtr; cf.hInstance = UnsafeNativeMethods.GetModuleHandle(null); cf.nSizeMin = minSize; if (maxSize == 0) { cf.nSizeMax = int.MaxValue; } else { cf.nSizeMax = maxSize; } Debug.Assert(cf.nSizeMin <= cf.nSizeMax, "min and max font sizes are the wrong way around"); if (!SafeNativeMethods.ChooseFont(cf)) { return(false); } NativeMethods.LOGFONT lfReturned = null; lfReturned = (NativeMethods.LOGFONT)UnsafeNativeMethods.PtrToStructure(logFontPtr, typeof(NativeMethods.LOGFONT)); if (lfReturned.lfFaceName != null && lfReturned.lfFaceName.Length > 0) { lf = lfReturned; UpdateFont(lf); UpdateColor(cf.rgbColors); } return(true); } finally { if (logFontPtr != IntPtr.Zero) { Marshal.FreeCoTaskMem(logFontPtr); } } }
/// <summary> /// 转为Windows颜色 /// </summary> /// <param name="color">颜色</param> /// <returns>Windows颜色值</returns> public static int ToWin32Color(this Color color) { return(ColorTranslator.ToWin32(color)); }
public static IntPtr FromColor(Color color) => (IntPtr)ColorTranslator.ToWin32(color);
public void ToWin32() { Assert.AreEqual(0x302010, ColorTranslator.ToWin32(Color.FromArgb(0x10, 0x20, 0x30))); Assert.AreEqual(unchecked ((int)0x3020bb), ColorTranslator.ToWin32(Color.FromArgb(0xee, 0xbb, 0x20, 0x30))); }
public override string ToText(Subtitle subtitle, string title) { const string header = @"[Script Info] ; This is a Sub Station Alpha v4 script. Title: {0} ScriptType: v4.00 Collisions: Normal PlayDepth: 0 [V4 Styles] Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding Style: Default,{1},{2},{3},65535,65535,-2147483640,{9},0,1,{4},{5},2,{6},{7},{8},0,1 [Events] Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"; const string headerNoStyles = @"[Script Info] ; This is a Sub Station Alpha v4 script. Title: {0} ScriptType: v4.00 Collisions: Normal PlayDepth: 0 [V4 Styles] Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, AlphaLevel, Encoding {1} [Events] Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"; const string timeCodeFormat = "{0}:{1:00}:{2:00}.{3:00}"; // h:mm:ss.cc const string paragraphWriteFormat = "Dialogue: Marked={4},{0},{1},{3},{5},{6},{7},{8},{9},{2}"; const string commentWriteFormat = "Comment: Marked={4},{0},{1},{3},{5},{6},{7},{8},{9},{2}"; var sb = new StringBuilder(); Color fontColor = Color.FromArgb(Configuration.Settings.SubtitleSettings.SsaFontColorArgb); bool isValidAssHeader = !string.IsNullOrEmpty(subtitle.Header) && subtitle.Header.Contains("[V4 Styles]"); var styles = new List <string>(); if (isValidAssHeader) { sb.AppendLine(subtitle.Header.Trim()); const string formatLine = "Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"; if (!subtitle.Header.Contains(formatLine)) { sb.AppendLine(formatLine); } styles = AdvancedSubStationAlpha.GetStylesFromHeader(subtitle.Header); } else if (!string.IsNullOrEmpty(subtitle.Header) && subtitle.Header.Contains("[V4+ Styles]")) { LoadStylesFromAdvancedSubstationAlpha(subtitle, title, subtitle.Header, headerNoStyles, sb); isValidAssHeader = true; styles = AdvancedSubStationAlpha.GetStylesFromHeader(subtitle.Header); } else if (subtitle.Header != null && subtitle.Header.Contains("http://www.w3.org/ns/ttml")) { LoadStylesFromTimedText10(subtitle, title, header, headerNoStyles, sb); } else { var ssa = Configuration.Settings.SubtitleSettings; string boldStyle = "0"; // 0=regular if (ssa.SsaFontBold) { boldStyle = "-1"; // -1 = true, 0 is false } sb.AppendLine(string.Format(header, title, ssa.SsaFontName, (int)ssa.SsaFontSize, ColorTranslator.ToWin32(fontColor), ssa.SsaOutline, ssa.SsaShadow, ssa.SsaMarginLeft, ssa.SsaMarginRight, ssa.SsaMarginTopBottom, boldStyle )); } foreach (Paragraph p in subtitle.Paragraphs) { string start = string.Format(timeCodeFormat, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, p.StartTime.Milliseconds / 10); string end = string.Format(timeCodeFormat, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, p.EndTime.Milliseconds / 10); string style = "Default"; string actor = "NTP"; if (!string.IsNullOrEmpty(p.Actor)) { actor = p.Actor; } string marginL = "0000"; if (!string.IsNullOrEmpty(p.MarginL) && Utilities.IsInteger(p.MarginL)) { marginL = p.MarginL.PadLeft(4, '0'); } string marginR = "0000"; if (!string.IsNullOrEmpty(p.MarginR) && Utilities.IsInteger(p.MarginR)) { marginR = p.MarginR.PadLeft(4, '0'); } string marginV = "0000"; if (!string.IsNullOrEmpty(p.MarginV) && Utilities.IsInteger(p.MarginV)) { marginV = p.MarginV.PadLeft(4, '0'); } string effect = ""; if (!string.IsNullOrEmpty(p.Effect)) { effect = p.Effect; } if (!string.IsNullOrEmpty(p.Extra) && isValidAssHeader && styles.Contains(p.Extra)) { style = p.Extra; } if (style == "Default") { style = "*Default"; } if (p.IsComment) { sb.AppendLine(string.Format(commentWriteFormat, start, end, AdvancedSubStationAlpha.FormatText(p), style, p.Layer, actor, marginL, marginR, marginV, effect)); } else { sb.AppendLine(string.Format(paragraphWriteFormat, start, end, AdvancedSubStationAlpha.FormatText(p), style, p.Layer, actor, marginL, marginR, marginV, effect)); } } return(sb.ToString().Trim()); }
private void RenderOnComposition(RenderContext context) { // Convert the clipping rectangle from floating to int version RectangleF rectClipF = context.Graphics.ClipBounds; Rectangle rectClip = new Rectangle((int)rectClipF.X, (int)rectClipF.Y, (int)rectClipF.Width, (int)rectClipF.Height); // No point drawing unless some of the client fits into the clipping area if (rectClip.IntersectsWith(ClientRectangle)) { // Get the hDC for the graphics instance and create a memory DC IntPtr gDC = context.Graphics.GetHdc(); IntPtr mDC = PI.CreateCompatibleDC(gDC); PI.BITMAPINFO bmi = new PI.BITMAPINFO(); bmi.biSize = Marshal.SizeOf(bmi); bmi.biWidth = ClientWidth; bmi.biHeight = -ClientHeight; bmi.biCompression = 0; bmi.biBitCount = 32; bmi.biPlanes = 1; // Create a device independant bitmp and select into the memory DC IntPtr hDIB = PI.CreateDIBSection(gDC, bmi, 0, 0, IntPtr.Zero, 0); PI.SelectObject(mDC, hDIB); // To call the renderer we need to convert from Win32 HDC to Graphics object using (Graphics bitmapG = Graphics.FromHdc(mDC)) { Rectangle renderClientRect = new Rectangle(0, 0, ClientWidth, ClientHeight); // Create new render context that uses the bitmap graphics instance using (RenderContext bitmapContext = new RenderContext(context.Control, bitmapG, renderClientRect, context.Renderer)) { // Finally we get the renderer to draw the background for the bitmap _mementoBack = context.Renderer.RenderRibbon.DrawRibbonTabContextTitle(_ribbon.RibbonShape, bitmapContext, renderClientRect, _ribbon.StateCommon.RibbonGeneral, this, _mementoBack); } } // Select the font for use when drawing IntPtr hFont = _contentProvider.GetContentShortTextFont(State).ToHfont(); PI.SelectObject(mDC, hFont); // Get renderer for the correct state VisualStyleRenderer renderer = new VisualStyleRenderer(VisualStyleElement.Window.Caption.Active); // Create structures needed for theme drawing call PI.RECT textBounds = new PI.RECT { left = TEXT_SIDE_GAP_COMPOSITION, top = 0, right = ClientWidth - (TEXT_SIDE_GAP_COMPOSITION * 2), bottom = ClientHeight }; PI.DTTOPTS dttOpts = new PI.DTTOPTS { dwSize = Marshal.SizeOf(typeof(PI.DTTOPTS)), dwFlags = PI.DTT_COMPOSITED | PI.DTT_GLOWSIZE | PI.DTT_TEXTCOLOR, crText = ColorTranslator.ToWin32(SystemColors.ActiveCaptionText), iGlowSize = (_ribbon.Enabled ? 12 : 2) }; // Always draw text centered const TextFormatFlags TEXT_FORMAT = TextFormatFlags.SingleLine | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis; // Perform actual drawing PI.DrawThemeTextEx(renderer.Handle, mDC, 0, 0, GetShortText(), -1, (int)TEXT_FORMAT, ref textBounds, ref dttOpts); // Copy to foreground PI.BitBlt(gDC, ClientLocation.X, ClientLocation.Y, ClientWidth, ClientHeight, mDC, 0, 0, 0x00CC0020); // Dispose of allocated objects PI.DeleteObject(hFont); PI.DeleteObject(hDIB); PI.DeleteDC(mDC); // Must remember to release the hDC context.Graphics.ReleaseHdc(gDC); } }
/// <summary> /// Draw text without a glowing background, for use on a composition element. /// </summary> /// <param name="g">Graphics reference.</param> /// <param name="text">Text to be drawn.</param> /// <param name="font">Font to use for text.</param> /// <param name="bounds">Bounding area for the text.</param> /// <param name="state">State of the source element.</param> /// <param name="color"><see cref="Color"/> of the text.</param> /// <param name="copyBackground">Should existing background be copied into the bitmap.</param> /// <param name="sf">StringFormat of the memento.</param> public static void DrawCompositionText(Graphics g, string text, Font font, Rectangle bounds, PaletteState state, Color color, bool copyBackground, StringFormat sf) { // Get the hDC for the graphics instance and create a memory DC IntPtr gDC = g.GetHdc(); try { IntPtr mDC = PI.CreateCompatibleDC(gDC); PI.BITMAPINFO bmi = new PI.BITMAPINFO { biWidth = bounds.Width, biHeight = -(bounds.Height), biCompression = 0, biBitCount = 32, biPlanes = 1 }; bmi.biSize = (uint)Marshal.SizeOf(bmi); // Create a device independent bitmap and select into the memory DC IntPtr hDIB = PI.CreateDIBSection(gDC, ref bmi, 0, out _, IntPtr.Zero, 0); PI.SelectObject(mDC, hDIB); if (copyBackground) { // Copy existing background into the bitmap PI.BitBlt(mDC, 0, 0, bounds.Width, bounds.Height, gDC, bounds.X, bounds.Y, 0x00CC0020); } // Select the font for use when drawing IntPtr hFont = font.ToHfont(); PI.SelectObject(mDC, hFont); // Get renderer for the correct state VisualStyleRenderer renderer = new VisualStyleRenderer(state == PaletteState.Normal ? VisualStyleElement.Window.Caption.Active : VisualStyleElement.Window.Caption.Inactive); // Create structures needed for theme drawing call PI.RECT textBounds = new PI.RECT { left = 0, top = 0, right = (bounds.Right - bounds.Left), bottom = (bounds.Bottom - bounds.Top) }; PI.DTTOPTS dttOpts = new PI.DTTOPTS { dwSize = Marshal.SizeOf(typeof(PI.DTTOPTS)), dwFlags = PI.DTT_COMPOSITED | PI.DTT_TEXTCOLOR, crText = ColorTranslator.ToWin32(color) }; // Always draw text centered TextFormatFlags textFormat = TextFormatFlags.SingleLine | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter; ////Seb | TextFormatFlags.EndEllipsis; // Perform actual drawing //PI.DrawThemeTextEx(renderer.Handle, // mDC, 0, 0, // text, -1, (int)StringFormatToFlags(sf), // ref textBounds, ref dttOpts); PI.DrawThemeTextEx(renderer.Handle, mDC, 0, 0, text, -1, (int)textFormat, ref textBounds, ref dttOpts); // Copy to foreground PI.BitBlt(gDC, bounds.Left, bounds.Top, bounds.Width, bounds.Height, mDC, 0, 0, 0x00CC0020); // Dispose of allocated objects PI.DeleteObject(hFont); PI.DeleteObject(hDIB); PI.DeleteDC(mDC); } catch { // ignored } finally { // Must remember to release the hDC g.ReleaseHdc(gDC); } }
private void FillRectDither(IntPtr dc, NativeMethods.RECT rc) { IntPtr hbrushOld = SafeNativeMethods.SelectObject(new HandleRef(null, dc), new HandleRef(this, hbrushDither)); if (hbrushOld != IntPtr.Zero) { int oldTextColor, oldBackColor; oldTextColor = SafeNativeMethods.SetTextColor(new HandleRef(null, dc), ColorTranslator.ToWin32(SystemColors.ControlLightLight)); oldBackColor = SafeNativeMethods.SetBkColor(new HandleRef(null, dc), ColorTranslator.ToWin32(SystemColors.Control)); SafeNativeMethods.PatBlt(new HandleRef(null, dc), rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, NativeMethods.PATCOPY); SafeNativeMethods.SetTextColor(new HandleRef(null, dc), oldTextColor); SafeNativeMethods.SetBkColor(new HandleRef(null, dc), oldBackColor); } }