Example #1
1
 public TextViewDialog()
 {
     InitializeComponent();
     this.sf = new StringFormat(StringFormat.GenericTypographic);
     sf.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
     tf = TextFormatFlags.NoPadding | TextFormatFlags.GlyphOverhangPadding;
 }
 public CalendarRendererBoxEventArgs(CalendarRendererEventArgs original, Rectangle bounds, string text, TextFormatFlags flags)
     : this(original)
 {
     Bounds = bounds;
     Text = text;
     Format |= flags;
 }
Example #3
0
		protected ButtonBase() : base()
		{
			flat_style	= FlatStyle.Standard;
			flat_button_appearance = new FlatButtonAppearance (this);
			this.image_key = string.Empty;
			this.text_image_relation = TextImageRelation.Overlay;
			this.use_mnemonic = true;
			use_visual_style_back_color = true;
			image_index	= -1;
			image		= null;
			image_list	= null;
			image_alignment	= ContentAlignment.MiddleCenter;
			ImeMode         = ImeMode.Disable;
			text_alignment	= ContentAlignment.MiddleCenter;
			is_default	= false;
			is_pressed	= false;
			text_format	= new StringFormat();
			text_format.Alignment = StringAlignment.Center;
			text_format.LineAlignment = StringAlignment.Center;
			text_format.HotkeyPrefix = HotkeyPrefix.Show;
			text_format.FormatFlags |= StringFormatFlags.LineLimit;

			text_format_flags = TextFormatFlags.HorizontalCenter;
			text_format_flags |= TextFormatFlags.VerticalCenter;
			text_format_flags |= TextFormatFlags.TextBoxControl;

			SetStyle (ControlStyles.ResizeRedraw | 
				ControlStyles.Opaque | 
				ControlStyles.UserMouse | 
				ControlStyles.SupportsTransparentBackColor | 
				ControlStyles.CacheText |
				ControlStyles.OptimizedDoubleBuffer, true);
			SetStyle (ControlStyles.StandardClick, false);
		}
		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 void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, Font font, Rectangle textBounds, TextFormatFlags flags, TextBoxState state)
 {
     InitializeRenderer((int) state);
     DrawBackground(g, bounds, state);
     Color foreColor = visualStyleRenderer.GetColor(ColorProperty.TextColor);
     TextRenderer.DrawText(g, textBoxText, font, textBounds, foreColor, flags);
 }
 public static void DrawTextBox(Graphics g, Rectangle bounds, string textBoxText, Font font, TextFormatFlags flags, TextBoxState state)
 {
     InitializeRenderer((int) state);
     Rectangle backgroundContentRectangle = visualStyleRenderer.GetBackgroundContentRectangle(g, bounds);
     backgroundContentRectangle.Inflate(-2, -2);
     DrawTextBox(g, bounds, textBoxText, font, backgroundContentRectangle, flags, state);
 }
		public static void DrawButton (Graphics g, Rectangle bounds, string buttonText, Font font, TextFormatFlags flags, Image image, Rectangle imageBounds, bool focused, PushButtonState state)
		{
			if (Application.RenderWithVisualStyles || always_use_visual_styles == true) {
				VisualStyleRenderer vsr = GetPushButtonRenderer (state);

				vsr.DrawBackground (g, bounds);

				if (image != null)
					vsr.DrawImage (g, imageBounds, image);
			} else {
				if (state == PushButtonState.Pressed)
					ControlPaint.DrawButton (g, bounds, ButtonState.Pushed);
				else
					ControlPaint.DrawButton (g, bounds, ButtonState.Normal);

				if (image != null)
					g.DrawImage (image, imageBounds);
			}

			Rectangle focus_rect = bounds;
			focus_rect.Inflate (-3, -3);

			if (focused)
				ControlPaint.DrawFocusRectangle (g, focus_rect);

			if (buttonText != String.Empty)
				if (state == PushButtonState.Disabled)
					TextRenderer.DrawText (g, buttonText, font, focus_rect, SystemColors.GrayText, flags);
				else
					TextRenderer.DrawText (g, buttonText, font, focus_rect, SystemColors.ControlText, flags);
		}
 public void DrawText(TextFormatFlags flags)
 {
     string text = this.header.Text;
     int width = TextRenderer.MeasureText(" ", this.font).Width;
     Rectangle bounds = Rectangle.Inflate(this.bounds, -width, 0);
     TextRenderer.DrawText(this.graphics, text, this.font, bounds, this.foreColor, flags);
 }
Example #9
0
 /// <summary>
 /// Initialises a new instance of the <see cref="CanvasText"/> class.
 /// </summary>
 public CanvasText()
     : base(CanvasItemLayout.ItemType.Component)
 {
     _stringFormat = TextFormatFlags.SingleLine | TextFormatFlags.WordEllipsis | TextFormatFlags.NoPadding | TextFormatFlags.Top | TextFormatFlags.NoPrefix;
     Alignment = CanvasTextAlign.Middle;
     Font = CanvasItemLayout.DefaultFont;
 }
		public static ThemedText CreateWithGlow(Graphics g, string text, Font font, Padding internalBounds,
			Rectangle bounds, Color color, TextFormatFlags formatFlags, int glowSize) {

			return Create(g, text, font, internalBounds, bounds, color, formatFlags,
				new IThemeTextOption[] { new GlowOption(glowSize) }
			);
		}
Example #11
0
 public DrawnText(String text, Font font, Rectangle rect, Color color, TextFormatFlags tf)
 {
     this.text = text;
     this.font = font;
     this.rectangle = rect;
     this.color = color;
     this.tf = tf;
 }
		public int UxThemeDrawThemeText (IntPtr hTheme, IDeviceContext dc, int iPartId, int iStateId, string text, TextFormatFlags textFlags, Rectangle bounds)
		{
			XplatUIWin32.RECT BoundsRect = XplatUIWin32.RECT.FromRectangle (bounds);

			int result = UXTheme.DrawThemeText (hTheme, dc.GetHdc (), iPartId, iStateId, text, text.Length, (uint)textFlags, 0, ref BoundsRect);
			dc.ReleaseHdc ();
			return result;
		}
		public static void DrawCheckBox (Graphics g, Point glyphLocation, Rectangle textBounds, string checkBoxText, Font font, TextFormatFlags flags, Image image, Rectangle imageBounds, bool focused, CheckBoxState state)
		{
			Rectangle bounds = new Rectangle (glyphLocation, GetGlyphSize (g, state));

			if (Application.RenderWithVisualStyles || always_use_visual_styles == true) {
				VisualStyleRenderer vsr = GetCheckBoxRenderer (state);

				vsr.DrawBackground (g, bounds);

				if (image != null)
					vsr.DrawImage (g, imageBounds, image);

				if (focused)
					ControlPaint.DrawFocusRectangle (g, textBounds);

				if (checkBoxText != String.Empty)
					if (state == CheckBoxState.CheckedDisabled || state == CheckBoxState.MixedDisabled || state == CheckBoxState.UncheckedDisabled)
						TextRenderer.DrawText (g, checkBoxText, font, textBounds, SystemColors.GrayText, flags);
					else
						TextRenderer.DrawText (g, checkBoxText, font, textBounds, SystemColors.ControlText, flags);
			} else {
				switch (state) {
					case CheckBoxState.CheckedDisabled:
					case CheckBoxState.MixedDisabled:
					case CheckBoxState.MixedPressed:
						ControlPaint.DrawCheckBox (g, bounds, ButtonState.Inactive | ButtonState.Checked);
						break;
					case CheckBoxState.CheckedHot:
					case CheckBoxState.CheckedNormal:
						ControlPaint.DrawCheckBox (g, bounds, ButtonState.Checked);
						break;
					case CheckBoxState.CheckedPressed:
						ControlPaint.DrawCheckBox (g, bounds, ButtonState.Pushed | ButtonState.Checked);
						break;
					case CheckBoxState.MixedHot:
					case CheckBoxState.MixedNormal:
						ControlPaint.DrawMixedCheckBox (g, bounds, ButtonState.Checked);
						break;
					case CheckBoxState.UncheckedDisabled:
					case CheckBoxState.UncheckedPressed:
						ControlPaint.DrawCheckBox (g, bounds, ButtonState.Inactive);
						break;
					case CheckBoxState.UncheckedHot:
					case CheckBoxState.UncheckedNormal:
						ControlPaint.DrawCheckBox (g, bounds, ButtonState.Normal);
						break;
				}

				if (image != null)
					g.DrawImage (image, imageBounds);

				if (focused)
					ControlPaint.DrawFocusRectangle (g, textBounds);

				if (checkBoxText != String.Empty)
					TextRenderer.DrawText (g, checkBoxText, font, textBounds, SystemColors.ControlText, flags);
			}
		}
        public WindowsGraphicsWrapper( IDeviceContext idc, TextFormatFlags flags)
        {
            if( idc is Graphics )
            {
                ApplyGraphicsProperties properties = ApplyGraphicsProperties.None;

                if( (flags & TextFormatFlags.PreserveGraphicsClipping) != 0)
                {
                    properties |= ApplyGraphicsProperties.Clipping;
                }

                if( (flags & TextFormatFlags.PreserveGraphicsTranslateTransform) != 0)
                {
                    properties |= ApplyGraphicsProperties.TranslateTransform;
                }

                // Create the WindowsGraphics from the Grahpics object only if Graphics properties need
                // to be reapplied to the DC wrapped by the WindowsGraphics.
                if( properties != ApplyGraphicsProperties.None )
                {
                    this.wg = WindowsGraphics.FromGraphics( idc as Graphics, properties);
                }
            }
            else
            {
                // If passed-in IDeviceContext object is a WindowsGraphics we can use it directly.
                this.wg = idc as WindowsGraphics;

                if( this.wg != null )
                {
                    // In this case we cache the idc to compare it against the wg in the Dispose method to avoid
                    // disposing of the wg.
                    this.idc = idc;
                }
            }

            if( this.wg == null )
            {
                // The IDeviceContext object is not a WindowsGraphics, or it is a custom IDeviceContext, or
                // it is a Graphics object but we did not need to re-apply Graphics propertiesto the hdc.  
                // So create the WindowsGraphics from the hdc directly. 
                // Cache the IDC so the hdc can be released on dispose.
                this.idc = idc;
                this.wg = WindowsGraphics.FromHdc( idc.GetHdc() );
            }

            // Set text padding on the WindowsGraphics (if any).
            if( (flags & TextFormatFlags.LeftAndRightPadding) != 0 )
            {
                wg.TextPadding = TextPaddingOptions.LeftAndRightPadding;
            }
            else if ((flags & TextFormatFlags.NoPadding) != 0 )
            {
                wg.TextPadding = TextPaddingOptions.NoPadding;
            }
            // else wg.TextPadding = TextPaddingOptions.GlyphOverhangPadding - the default value.
        }
 public void DrawText(TextFormatFlags flags)
 {
     string text = (this.itemIndex == -1) ? this.item.Text : this.subItem.Text;
     Font font = (this.itemIndex == -1) ? this.item.Font : this.subItem.Font;
     Color foreColor = (this.itemIndex == -1) ? this.item.ForeColor : this.subItem.ForeColor;
     int width = TextRenderer.MeasureText(" ", font).Width;
     Rectangle bounds = Rectangle.Inflate(this.bounds, -width, 0);
     TextRenderer.DrawText(this.graphics, text, font, bounds, foreColor, flags);
 }
Example #16
0
 private void InstantiateNew(string text, Font font,
     Color foreColor, Color backColor, TextFormatFlags flags)
 {
     _text = text;
     _font = font;
     _foreColor = foreColor;
     _backColor = backColor;
     _flags = flags;
 }
Example #17
0
        public MirLabel()
        {
            DrawControlTexture = true;
            _drawFormat = TextFormatFlags.WordBreak;

            _font = new Font(Settings.FontName, 8F);
            _outLine = true;
            _outLineColour = Color.Black;
            _text = string.Empty;
        }
    public TipText(Graphics graphics, Font font, string text)
      : base(graphics)
    {
      if (text != null && text.Length > short.MaxValue)
        throw new ArgumentException("TipText: text too long (max. is " + short.MaxValue + " characters)", "text");

      tipFont = font; tipText = text;
      Color = SystemColors.InfoText;
      textFormatFlags = TextFormatFlags.Default;
    }
        /// <include file='doc\ToolStripItemTextRenderEventArgs.uex' path='docs/doc[@for="ToolStripItemTextRenderEventArgs.ToolStripItemTextRenderEventArgs"]/*' />
        /// <devdoc>
        /// This class represents all the information to render the winbar
        /// </devdoc>
        public ToolStripItemTextRenderEventArgs(Graphics g, ToolStripItem item, string text, Rectangle textRectangle, Color textColor, Font textFont, TextFormatFlags format) : base(g, item) {
            this.text = text;
            this.textRectangle = textRectangle;
            this.defaultTextColor = textColor;
            this.textFont = textFont;
            this.textAlignment = item.TextAlign;
            this.textFormat = format;
            textDirection = item.TextDirection;

        }
Example #20
0
 public TextPart(XmlElement element, ChatMessagePart parent = null, Font font = null)
     : base(parent, font)
 {
     stf = StringFormat.GenericTypographic;
     stf.FormatFlags |= StringFormatFlags.NoClip;
     formatFlags = TextFormatFlags.Default | TextFormatFlags.TextBoxControl | TextFormatFlags.NoPadding | TextFormatFlags.NoPrefix | TextFormatFlags.NoClipping;
     Text = XML = element.InnerText;
     PreParse(element);
     InitText();
 }
 /// <include file='doc\ToolStripItemTextRenderEventArgs.uex' path='docs/doc[@for="ToolStripItemTextRenderEventArgs.ToolStripItemTextRenderEventArgs"]/*' />
 /// <devdoc>
 /// This class represents all the information to render the winbar
 /// </devdoc>
 public ToolStripItemTextRenderEventArgs(Graphics g, ToolStripItem item, string text, Rectangle textRectangle, Color textColor, Font textFont, ContentAlignment textAlign) : base(g, item) {
     this.text = text;
     this.textRectangle = textRectangle;
     this.defaultTextColor = textColor;
     this.textFont = textFont;
     this.textFormat = ToolStripItemInternalLayout.ContentAlignToTextFormat(textAlign, item.RightToLeft == RightToLeft.Yes); 
     
     // in 2K and XP++ hide underlined &File unless ALT is pressed
     this.textFormat = (item.ShowKeyboardCues) ? textFormat : textFormat | TextFormatFlags.HidePrefix;
     textDirection = item.TextDirection;
 }
 public static void DrawGroupBox(Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, TextFormatFlags flags, GroupBoxState state)
 {
     if (RenderWithVisualStyles)
     {
         DrawThemedGroupBoxWithText(g, bounds, groupBoxText, font, textColor, flags, state);
     }
     else
     {
         DrawUnthemedGroupBoxWithText(g, bounds, groupBoxText, font, textColor, flags, state);
     }
 }
Example #23
0
        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);
        }
Example #24
0
        //
        // Summary:
        //     Draws the specified text at the specified location using the specified device
        //     context, font, color, and formatting instructions.
        //
        // Parameters:
        //   foreColor:
        //     The System.Drawing.Color to apply to the drawn text.
        //
        //   font:
        //     The System.Drawing.Font to apply to the drawn text.
        //
        //   dc:
        //     The device context in which to draw the text.
        //
        //   pt:
        //     The System.Drawing.Point that represents the upper-left corner of the drawn
        //     text.
        //
        //   flags:
        //     A bitwise combination of the System.Drawing.GDI.TextFormatFlags values.
        //
        //   text:
        //     The text to draw.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     dc is null.
        public static void DrawText(IDeviceContext dc, string text, Font font, Rectangle rc, Color foreColor, TextFormatFlags flags)
        {
            Graphics grfx = dc as Graphics;

            if (grfx != null)
            {
                rc.X += (int) grfx.Transform.OffsetX;
                rc.Y += (int) grfx.Transform.OffsetY;
            }
            TextRenderer.DrawText(dc, text, font, rc, foreColor, flags);
        }
Example #25
0
		public static void DrawGroupBox (Graphics g, Rectangle bounds, string groupBoxText, Font font, Color textColor, TextFormatFlags flags, GroupBoxState state)
		{
			Size font_size = TextRenderer.MeasureText (groupBoxText, font);

			if (Application.RenderWithVisualStyles || always_use_visual_styles == true) {
				VisualStyleRenderer vsr;
				Rectangle new_bounds;

				switch (state) {
					case GroupBoxState.Normal:
					default:
						vsr = new VisualStyleRenderer (VisualStyleElement.Button.GroupBox.Normal);
						new_bounds = new Rectangle (bounds.Left, bounds.Top + (int)(font_size.Height / 2) - 1, bounds.Width, bounds.Height - (int)(font_size.Height / 2) + 1);
						break;
					case GroupBoxState.Disabled:
						vsr = new VisualStyleRenderer (VisualStyleElement.Button.GroupBox.Disabled);
						new_bounds = new Rectangle (bounds.Left, bounds.Top + (int)(font_size.Height / 2) - 2, bounds.Width, bounds.Height - (int)(font_size.Height / 2) + 2);
						break;
				}

				if (groupBoxText == String.Empty)
					vsr.DrawBackground (g, bounds);
				else
					vsr.DrawBackgroundExcludingArea (g, new_bounds, new Rectangle (bounds.Left + 9, bounds.Top, font_size.Width - 3, font_size.Height));

				if (textColor == Color.Empty)
					textColor = vsr.GetColor (ColorProperty.TextColor);

				if (groupBoxText != String.Empty)
					TextRenderer.DrawText (g, groupBoxText, font, new Point (bounds.Left + 8, bounds.Top), textColor, flags);
			}
			else {
				// MS has a pretty big bug when rendering the non-visual styles group box.  Instead of using the height
				// part of the bounds as height, they use it as the bottom, so the boxes are drawn in completely different
				// places.  Rather than emulate this bug, we do it correctly.  After googling for a while, I don't think
				// anyone has ever actually used this class for anything, so it should be fine.  :)
				Rectangle new_bounds = new Rectangle (bounds.Left, bounds.Top + (int)(font_size.Height / 2), bounds.Width, bounds.Height - (int)(font_size.Height / 2));
				
				// Don't paint over the background where we are going to put the text
				Region old_clip = g.Clip;
				g.SetClip (new Rectangle (bounds.Left + 9, bounds.Top, font_size.Width - 3, font_size.Height), System.Drawing.Drawing2D.CombineMode.Exclude);
				
				ControlPaint.DrawBorder3D (g, new_bounds, Border3DStyle.Etched);
				
				g.Clip = old_clip;

				if (groupBoxText != String.Empty) {
					if (textColor == Color.Empty)
						textColor = state == GroupBoxState.Normal ? SystemColors.ControlText :
							SystemColors.GrayText;
					TextRenderer.DrawText (g, groupBoxText, font, new Point (bounds.Left + 8, bounds.Top), textColor, flags);
				}
			}
		}
Example #26
0
        protected BaseTextControl()
        {
            IncrementalSearchEnabled = true;
            _focusPen = new Pen(Color.Black);
            _focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;

            _format = new StringFormat(StringFormatFlags.LineLimit | StringFormatFlags.NoClip | StringFormatFlags.FitBlackBox | StringFormatFlags.MeasureTrailingSpaces);
            _baseFormatFlags = TextFormatFlags.PreserveGraphicsClipping |
                           TextFormatFlags.PreserveGraphicsTranslateTransform;
            SetFormatFlags();
            LeftMargin = 3;
        }
 public static void DrawTabItem(Graphics g, Rectangle bounds, string tabItemText, Font font, TextFormatFlags flags, bool focused, TabItemState state)
 {
     InitializeRenderer(VisualStyleElement.Tab.TabItem.Normal, (int) state);
     visualStyleRenderer.DrawBackground(g, bounds);
     Rectangle rectangle = Rectangle.Inflate(bounds, -3, -3);
     Color foreColor = visualStyleRenderer.GetColor(ColorProperty.TextColor);
     TextRenderer.DrawText(g, tabItemText, font, rectangle, foreColor, flags);
     if (focused)
     {
         ControlPaint.DrawFocusRectangle(g, rectangle);
     }
 }
Example #28
0
        public LinkPart(ChatMessagePart parent=null,Font font = null)
            : base(parent,font)
        {
            if (font == null)
                defaultFont = new Font(parent.Font, parent.Font.Style | FontStyle.Underline);
            else
                defaultFont = new Font(font, font.Style | FontStyle.Underline);

            formatFlags = TextFormatFlags.Default | TextFormatFlags.TextBoxControl | TextFormatFlags.NoPadding | TextFormatFlags.NoPrefix;

            clickedFont = defaultFont;
        }
Example #29
0
        internal Area(Graphics g, Rectangle bounds, string text, Color textColor, Color backColor, Color borderColor)
        {
            _graphics = g;
            _bounds = bounds;
            _text = text;
            _textColor = textColor;
            _backgroundColor = backColor;
            _borderColor = borderColor;
            _borderWidth = 1;

            _textFlags |= TextFormatFlags.HorizontalCenter;
            _textFlags |= TextFormatFlags.VerticalCenter;
        }
        protected BaseTextControl()
        {
            IncrementalSearchEnabled = true;
            _focusPen = new Pen(Color.Black);
            _focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;

              // ml: added flags for vertical centering and no wrapping.
            _format = new StringFormat(StringFormatFlags.NoClip | StringFormatFlags.FitBlackBox |
            StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap);
            _baseFormatFlags = TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.VerticalCenter |
                           TextFormatFlags.PreserveGraphicsTranslateTransform;
            SetFormatFlags();
            LeftMargin = 3;
        }
        public int UxThemeGetThemeTextExtent(IntPtr hTheme, IDeviceContext dc, int iPartId, int iStateId, string textToDraw, TextFormatFlags flags, out Rectangle result)
        {
            XplatUIWin32.RECT retval;

            int hresult = UXTheme.GetThemeTextExtent(hTheme, dc.GetHdc(), iPartId, iStateId, textToDraw, textToDraw.Length, (int)flags, 0, out retval);

            dc.ReleaseHdc();

            result = retval.ToRectangle();
            return(hresult);
        }
        /// <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);
            }
        }
Example #33
0
        protected virtual void OnPaintForeground(PaintEventArgs e)
        {
            Color color = MetroPaint.BorderColor.Button.Normal(this.Theme);
            Color foreColor;

            if (this.isHovered && !this.isPressed && base.Enabled)
            {
                foreColor = MetroPaint.ForeColor.Tile.Hover(this.Theme);
            }
            else if (this.isHovered && this.isPressed && base.Enabled)
            {
                foreColor = MetroPaint.ForeColor.Tile.Press(this.Theme);
            }
            else if (!base.Enabled)
            {
                foreColor = MetroPaint.ForeColor.Tile.Disabled(this.Theme);
            }
            else
            {
                foreColor = MetroPaint.ForeColor.Tile.Normal(this.Theme);
            }
            if (this.useCustomForeColor)
            {
                foreColor = this.ForeColor;
            }
            if (this.isPressed || this.isHovered || this.isFocused)
            {
                using (Pen pen = new Pen(color))
                {
                    pen.Width = 3f;
                    Rectangle rect = new Rectangle(1, 1, base.Width - 3, base.Height - 3);
                    e.Graphics.DrawRectangle(pen, rect);
                }
            }
            e.Graphics.SmoothingMode      = SmoothingMode.HighQuality;
            e.Graphics.CompositingQuality = CompositingQuality.HighQuality;
            if (this.useTileImage && this.tileImage != null)
            {
                ContentAlignment contentAlignment = this.tileImageAlign;
                Rectangle        rect2;
                if (contentAlignment <= ContentAlignment.MiddleCenter)
                {
                    switch (contentAlignment)
                    {
                    case ContentAlignment.TopLeft:
                        rect2 = new Rectangle(new Point(0, 0), new Size(this.TileImage.Width, this.TileImage.Height));
                        goto IL_430;

                    case ContentAlignment.TopCenter:
                        rect2 = new Rectangle(new Point(base.Width / 2 - this.TileImage.Width / 2, 0), new Size(this.TileImage.Width, this.TileImage.Height));
                        goto IL_430;

                    case (ContentAlignment)3:
                        break;

                    case ContentAlignment.TopRight:
                        rect2 = new Rectangle(new Point(base.Width - this.TileImage.Width, 0), new Size(this.TileImage.Width, this.TileImage.Height));
                        goto IL_430;

                    default:
                        if (contentAlignment == ContentAlignment.MiddleLeft)
                        {
                            rect2 = new Rectangle(new Point(0, base.Height / 2 - this.TileImage.Height / 2), new Size(this.TileImage.Width, this.TileImage.Height));
                            goto IL_430;
                        }
                        if (contentAlignment == ContentAlignment.MiddleCenter)
                        {
                            rect2 = new Rectangle(new Point(base.Width / 2 - this.TileImage.Width / 2, base.Height / 2 - this.TileImage.Height / 2), new Size(this.TileImage.Width, this.TileImage.Height));
                            goto IL_430;
                        }
                        break;
                    }
                }
                else if (contentAlignment <= ContentAlignment.BottomLeft)
                {
                    if (contentAlignment == ContentAlignment.MiddleRight)
                    {
                        rect2 = new Rectangle(new Point(base.Width - this.TileImage.Width, base.Height / 2 - this.TileImage.Height / 2), new Size(this.TileImage.Width, this.TileImage.Height));
                        goto IL_430;
                    }
                    if (contentAlignment == ContentAlignment.BottomLeft)
                    {
                        rect2 = new Rectangle(new Point(0, base.Height - this.TileImage.Height), new Size(this.TileImage.Width, this.TileImage.Height));
                        goto IL_430;
                    }
                }
                else
                {
                    if (contentAlignment == ContentAlignment.BottomCenter)
                    {
                        rect2 = new Rectangle(new Point(base.Width / 2 - this.TileImage.Width / 2, base.Height - this.TileImage.Height), new Size(this.TileImage.Width, this.TileImage.Height));
                        goto IL_430;
                    }
                    if (contentAlignment == ContentAlignment.BottomRight)
                    {
                        rect2 = new Rectangle(new Point(base.Width - this.TileImage.Width, base.Height - this.TileImage.Height), new Size(this.TileImage.Width, this.TileImage.Height));
                        goto IL_430;
                    }
                }
                rect2 = new Rectangle(new Point(0, 0), new Size(this.TileImage.Width, this.TileImage.Height));
IL_430:
                e.Graphics.DrawImage(this.TileImage, rect2);
            }
            if (this.TileCount > 0 && this.paintTileCount)
            {
                Size size = TextRenderer.MeasureText(this.TileCount.ToString(), MetroFonts.TileCount);
                e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
                TextRenderer.DrawText(e.Graphics, this.TileCount.ToString(), MetroFonts.TileCount, new Point(base.Width - size.Width, 0), foreColor);
                e.Graphics.TextRenderingHint = TextRenderingHint.SystemDefault;
            }
            TextRenderer.MeasureText(this.Text, MetroFonts.Tile(this.tileTextFontSize, this.tileTextFontWeight));
            TextFormatFlags flags           = MetroPaint.GetTextFormatFlags(this.TextAlign, true) | TextFormatFlags.LeftAndRightPadding | TextFormatFlags.EndEllipsis;
            Rectangle       clientRectangle = base.ClientRectangle;

            if (this.isPressed)
            {
                clientRectangle.Inflate(-4, -12);
            }
            else
            {
                clientRectangle.Inflate(-2, -10);
            }
            TextRenderer.DrawText(e.Graphics, this.Text, MetroFonts.Tile(this.tileTextFontSize, this.tileTextFontWeight), clientRectangle, foreColor, flags);
        }
        /// <include file='doc\DataGridViewCell.uex' path='docs/doc[@for="DataGridViewCell.GetPreferredSize"]/*' />
        protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
        {
            if (this.DataGridView == null)
            {
                return(new Size(-1, -1));
            }

            if (cellStyle == null)
            {
                throw new ArgumentNullException(nameof(cellStyle));
            }

            Size      preferredSize;
            Rectangle borderWidthsRect              = this.StdBorderWidths;
            int       borderAndPaddingWidths        = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal;
            int       borderAndPaddingHeights       = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical;
            DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize);
            object formattedValue  = GetFormattedValue(rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.PreferredSize);
            string formattedString = formattedValue as string;

            if (string.IsNullOrEmpty(formattedString))
            {
                formattedString = " ";
            }
            TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);

            if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1)
            {
                switch (freeDimension)
                {
                case DataGridViewFreeDimension.Width:
                {
                    preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics,
                                                                               formattedString,
                                                                               cellStyle.Font,
                                                                               Math.Max(1, constraintSize.Height - borderAndPaddingHeights - DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping - DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom),
                                                                               flags),
                                             0);
                    break;
                }

                case DataGridViewFreeDimension.Height:
                {
                    preferredSize = new Size(0,
                                             DataGridViewCell.MeasureTextHeight(graphics,
                                                                                formattedString,
                                                                                cellStyle.Font,
                                                                                Math.Max(1, constraintSize.Width - borderAndPaddingWidths - DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft - DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight),
                                                                                flags));
                    break;
                }

                default:
                {
                    preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics,
                                                                              formattedString,
                                                                              cellStyle.Font,
                                                                              5.0F,
                                                                              flags);
                    break;
                }
                }
            }
            else
            {
                switch (freeDimension)
                {
                case DataGridViewFreeDimension.Width:
                {
                    preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width,
                                             0);
                    break;
                }

                case DataGridViewFreeDimension.Height:
                {
                    preferredSize = new Size(0,
                                             DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Height);
                    break;
                }

                default:
                {
                    preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags);
                    break;
                }
                }
            }

            if (freeDimension != DataGridViewFreeDimension.Height)
            {
                preferredSize.Width += DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft + DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight + borderAndPaddingWidths;
                if (this.DataGridView.ShowCellErrors)
                {
                    // Making sure that there is enough room for the potential error icon
                    preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth);
                }
            }
            if (freeDimension != DataGridViewFreeDimension.Width)
            {
                int verticalTextMarginTop = cellStyle.WrapMode == DataGridViewTriState.True ? DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping : DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithoutWrapping;
                preferredSize.Height += verticalTextMarginTop + DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom + borderAndPaddingHeights;
                if (this.DataGridView.ShowCellErrors)
                {
                    // Making sure that there is enough room for the potential error icon
                    preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight);
                }
            }
            return(preferredSize);
        }
Example #35
0
        /// <summary>
        /// Implements the custom drawing for the button.
        /// </summary>
        /// <param name="paintEvent">The paint event args.</param>
        protected override void OnPaint(PaintEventArgs paintEvent)
        {
            GraphicsPath gp = CreateOutlinePath(paintEvent.Graphics);

            if (state == State.Disabled)
            {
                using (Brush b = new SolidBrush(Color.FromArgb(128, BackColor)))
                {
                    paintEvent.Graphics.FillRectangle(b, ClientRectangle);
                }
            }
            else
            {
                DrawHighlight(paintEvent.Graphics, gp);
            }
            using (Pen p = new Pen(Enabled ? highlightColor : Color.FromArgb(128, Color.FromKnownColor(KnownColor.GrayText)),
                                   Enabled ? hightlightWidth : 0.1f))
            {
                paintEvent.Graphics.DrawPath(p, gp);
            }

            // ReSharper disable RedundantCast
            // This cast is done to enable Mono to package this
            int offset = (state == State.Pushed) ? (int)buttonDepress : 0;
            // ReSharper restore RedundantCast

            RectangleF available = new RectangleF(ClientRectangle.Location, ClientRectangle.Size);
            // Draw the image...
            Image drawImage = GetDrawImage();

            if (drawImage != null)
            {
                // Figure out where to stick the image.
                RectangleF imageRect       = GetAlignedRectangle(available, drawImage.Size, ImageAlign);
                float      imageAndMargins = imageRect.Width + (2f * imageMargin);
                switch (ImageAlign)
                {
                case ContentAlignment.BottomLeft:
                case ContentAlignment.MiddleLeft:
                case ContentAlignment.TopLeft:
                    available.Width -= imageAndMargins;
                    available.Offset(imageAndMargins, 0f);
                    imageRect.Offset(imageMargin, 0f);
                    break;

                case ContentAlignment.BottomRight:
                case ContentAlignment.MiddleRight:
                case ContentAlignment.TopRight:
                    available.Width -= imageAndMargins;
                    imageRect.Offset(-imageMargin, 0f);
                    break;
                }
                if (offset != 0)
                {
                    imageRect.Offset(offset, offset);
                }
                paintEvent.Graphics.DrawImage(drawImage, imageRect);
            }

            // Now fill in the text
            {
                Size headlineSize  = TextRenderer.MeasureText(paintEvent.Graphics, Text, Font);
                Size subscriptSize = TextRenderer.MeasureText(paintEvent.Graphics, subscript, subscriptFont);
                Size combined      = new Size(Math.Max(headlineSize.Width, subscriptSize.Width),
                                              headlineSize.Height + subscriptSize.Height + textGap);

                Rectangle textRect = Rectangle.Round(GetAlignedRectangle(available, combined, TextAlign));
                // Draw the headline text...
                if (offset != 0)
                {
                    textRect.Offset(offset, offset);
                }
                TextFormatFlags tf = TextFormatFlags.WordEllipsis;
                if (!showUnderLine)
                {
                    tf |= TextFormatFlags.HidePrefix;
                }
                Color textColor = Enabled ? ForeColor : Color.FromKnownColor(KnownColor.GrayText);

                TextRenderer.DrawText(paintEvent.Graphics, Text, Font,
                                      new Rectangle(textRect.X, textRect.Y, textRect.Width, headlineSize.Height),
                                      textColor, Color.Transparent, tf);
                // Draw the subscript text...
                TextRenderer.DrawText(paintEvent.Graphics, subscript, subscriptFont,
                                      new Rectangle(textRect.X, textRect.Y + headlineSize.Height + textGap, textRect.Width, subscriptSize.Height),
                                      textColor, Color.Transparent, TextFormatFlags.WordEllipsis);
            }
        }
Example #36
0
        private void ListView_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
        {
            // We draw the current line of items (= item with sub items) on a temp bitmap, then draw the bitmap at once. This is to reduce flickering.
            Bitmap   _bitmap   = new Bitmap(e.Item.Bounds.Width, e.Item.Bounds.Height);
            Graphics _graphics = Graphics.FromImage(_bitmap);

            if (e.ItemState.HasFlag(ListViewItemStates.Selected))
            {
                _graphics.FillRectangle(new SolidBrush(_itemSelected), new Rectangle(new Point(e.Bounds.X, 0), e.Bounds.Size));
            }
            else if (e.Bounds.Contains(LastPosition) && (MouseState == MouseStates.Hover))
            {
                _graphics.FillRectangle(new SolidBrush(_itemHover), new Rectangle(new Point(e.Bounds.X, 0), e.Bounds.Size));
            }
            else
            {
                _graphics.FillRectangle(new SolidBrush(_itemEnabled), new Rectangle(new Point(e.Bounds.X, 0), e.Bounds.Size));
            }

            // Draw separator
            // graphics.DrawLine(new Pen(Color.Red), e.Bounds.Left, 0, e.Bounds.Right, 0);
            foreach (ListViewItem.ListViewSubItem subItem in e.Item.SubItems)
            {
                // Draw text
                _graphics.DrawString(subItem.Text, Font, new SolidBrush(Color.Black), new Rectangle(subItem.Bounds.X + _itemPadding, _itemPadding, subItem.Bounds.Width - (2 * _itemPadding), subItem.Bounds.Height - (2 * _itemPadding)), GetStringFormat());
            }

            // Draw the item text for views other than the Details view
            if (_listView.View != View.Details)
            {
                e.DrawText();
            }

            TextFormatFlags _textFormatFlags = TextFormatFlags.Left;
            StringFormat    _stringFormat    = new StringFormat();

            // Store the column text alignment, letting it default
            // to Left if it has not been set to Center or Right.
            switch (e.Header.TextAlign)
            {
            case HorizontalAlignment.Center:
            {
                _stringFormat.Alignment = StringAlignment.Center;
                _textFormatFlags        = TextFormatFlags.HorizontalCenter;
                break;
            }

            case HorizontalAlignment.Right:
            {
                _stringFormat.Alignment = StringAlignment.Far;
                _textFormatFlags        = TextFormatFlags.Right;
                break;
            }

            case HorizontalAlignment.Left:
            {
                break;
            }

            default:
            {
                throw new ArgumentOutOfRangeException();
            }
            }

            // Draw the text and background for a sub item with a
            // negative value.
            double _subItemValue;

            if ((e.ColumnIndex > 0) && double.TryParse(e.SubItem.Text, NumberStyles.Currency, NumberFormatInfo.CurrentInfo, out _subItemValue) && (_subItemValue < 0))
            {
                // Unless the item is selected, draw the standard
                // background to make it stand out from the gradient.
                if ((e.ItemState & ListViewItemStates.Selected) == 0)
                {
                    e.DrawBackground();
                }

                // Draw the sub item text in red to highlight it.
                _graphics.DrawString(e.SubItem.Text, Font, Brushes.Red, e.Bounds, _stringFormat);

                return;
            }

            e.Graphics.DrawImage((Image)_bitmap.Clone(), new Point(0, e.Item.Bounds.Location.Y));

            // Draw normal text for a sub item with a non negative
            // or non numerical value.
            e.DrawText(_textFormatFlags);

            _graphics.Dispose();
            _bitmap.Dispose();
        }
        // PaintPrivate is used in three places that need to duplicate the paint code:
        // 1. DataGridViewCell::Paint method
        // 2. DataGridViewCell::GetContentBounds
        // 3. DataGridViewCell::GetErrorIconBounds
        //
        // if computeContentBounds is true then PaintPrivate returns the contentBounds
        // else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds
        // else it returns Rectangle.Empty;
        private Rectangle PaintPrivate(Graphics graphics,
                                       Rectangle clipBounds,
                                       Rectangle cellBounds,
                                       int rowIndex,
                                       DataGridViewElementStates cellState,
                                       object formattedValue,
                                       string errorText,
                                       DataGridViewCellStyle cellStyle,
                                       DataGridViewAdvancedBorderStyle advancedBorderStyle,
                                       DataGridViewPaintParts paintParts,
                                       bool computeContentBounds,
                                       bool computeErrorIconBounds,
                                       bool paint)
        {
            // Parameter checking.
            // One bit and one bit only should be turned on
            Debug.Assert(paint || computeContentBounds || computeErrorIconBounds);
            Debug.Assert(!paint || !computeContentBounds || !computeErrorIconBounds);
            Debug.Assert(!computeContentBounds || !computeErrorIconBounds || !paint);
            Debug.Assert(!computeErrorIconBounds || !paint || !computeContentBounds);
            Debug.Assert(cellStyle != null);

            // If computeContentBounds == TRUE then resultBounds will be the contentBounds.
            // If computeErrorIconBounds == TRUE then resultBounds will be the error icon bounds.
            // Else resultBounds will be Rectangle.Empty;
            Rectangle resultBounds = Rectangle.Empty;

            if (paint && DataGridViewCell.PaintBorder(paintParts))
            {
                PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
            }

            Rectangle borderWidths = BorderWidths(advancedBorderStyle);
            Rectangle valBounds    = cellBounds;

            valBounds.Offset(borderWidths.X, borderWidths.Y);
            valBounds.Width  -= borderWidths.Right;
            valBounds.Height -= borderWidths.Bottom;

            SolidBrush br;

            Point ptCurrentCell = this.DataGridView.CurrentCellAddress;
            bool  cellCurrent   = ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex;
            bool  cellEdited    = cellCurrent && this.DataGridView.EditingControl != null;
            bool  cellSelected  = (cellState & DataGridViewElementStates.Selected) != 0;

            if (DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected && !cellEdited)
            {
                br = this.DataGridView.GetCachedBrush(cellStyle.SelectionBackColor);
            }
            else
            {
                br = this.DataGridView.GetCachedBrush(cellStyle.BackColor);
            }

            if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255 && valBounds.Width > 0 && valBounds.Height > 0)
            {
                graphics.FillRectangle(br, valBounds);
            }

            if (cellStyle.Padding != Padding.Empty)
            {
                if (this.DataGridView.RightToLeftInternal)
                {
                    valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
                }
                else
                {
                    valBounds.Offset(cellStyle.Padding.Left, cellStyle.Padding.Top);
                }
                valBounds.Width  -= cellStyle.Padding.Horizontal;
                valBounds.Height -= cellStyle.Padding.Vertical;
            }

            if (paint && cellCurrent && !cellEdited)
            {
                // Draw focus rectangle
                if (DataGridViewCell.PaintFocus(paintParts) &&
                    this.DataGridView.ShowFocusCues &&
                    this.DataGridView.Focused &&
                    valBounds.Width > 0 &&
                    valBounds.Height > 0)
                {
                    ControlPaint.DrawFocusRectangle(graphics, valBounds, Color.Empty, br.Color);
                }
            }

            Rectangle errorBounds     = valBounds;
            string    formattedString = formattedValue as string;

            if (formattedString != null && ((paint && !cellEdited) || computeContentBounds))
            {
                // Font independent margins
                int verticalTextMarginTop = cellStyle.WrapMode == DataGridViewTriState.True ? DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithWrapping : DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginTopWithoutWrapping;
                valBounds.Offset(DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft, verticalTextMarginTop);
                valBounds.Width  -= DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginLeft + DATAGRIDVIEWTEXTBOXCELL_horizontalTextMarginRight;
                valBounds.Height -= verticalTextMarginTop + DATAGRIDVIEWTEXTBOXCELL_verticalTextMarginBottom;
                if (valBounds.Width > 0 && valBounds.Height > 0)
                {
                    TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
                    if (paint)
                    {
                        if (DataGridViewCell.PaintContentForeground(paintParts))
                        {
                            if ((flags & TextFormatFlags.SingleLine) != 0)
                            {
                                flags |= TextFormatFlags.EndEllipsis;
                            }
                            TextRenderer.DrawText(graphics,
                                                  formattedString,
                                                  cellStyle.Font,
                                                  valBounds,
                                                  cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor,
                                                  flags);
                        }
                    }
                    else
                    {
                        resultBounds = DataGridViewUtilities.GetTextBounds(valBounds, formattedString, flags, cellStyle);
                    }
                }
            }
            else if (computeErrorIconBounds)
            {
                if (!string.IsNullOrEmpty(errorText))
                {
                    resultBounds = ComputeErrorIconBounds(errorBounds);
                }
            }
            else
            {
                Debug.Assert(cellEdited || formattedString == null);
                Debug.Assert(paint || computeContentBounds);
            }

            if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts))
            {
                PaintErrorIcon(graphics, cellStyle, rowIndex, cellBounds, errorBounds, errorText);
            }

            return(resultBounds);
        }
Example #38
0
 public static Size MeasureText(IDeviceContext dc, string text, Font font, Size proposedSize, TextFormatFlags flags)
 {
     return(MeasureTextInternal(dc, text, font, proposedSize, flags, false));
 }
Example #39
0
        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)
            {
                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 (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);
                }

                StringFormat sf = FlagsToStringFormat(flags);

                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();
                }
            }
        }
            ///  GetTextSize
            ///  Given constraints, format flags a font and text, determine the size of the string
            ///  employs an MRU of the last several constraints passed in via a ring-buffer of size MaxCacheSize.
            ///  Assumes Text and TextFormatFlags are the same, if either were to change, a call to
            ///  InvalidateCache should be made
            public Size GetTextSize(string?text, Font?font, Size proposedConstraints, TextFormatFlags flags)
            {
                if (!TextRequiresWordBreak(text, font, proposedConstraints, flags))
                {
                    // Text fits within proposed width

                    // IF we're here, this means we've got text that can fit into the proposedConstraints
                    // without wrapping.  We've determined this because our

                    // as a side effect of calling TextRequiresWordBreak,
                    // unconstrainedPreferredSize is set.
                    return(_unconstrainedPreferredSize);
                }
                else
                {
                    // Text does NOT fit within proposed width - requires WordBreak

                    // IF we're here, this means that the wrapping width is smaller
                    // than our max width.  For example: we measure the text with infinite
                    // bounding box and we determine the width to fit all the characters
                    // to be 200 px wide.  We would come here only for proposed widths less
                    // than 200 px.

                    // Create our ring buffer if we don't have one
                    if (_sizeCacheList is null)
                    {
                        _sizeCacheList = new PreferredSizeCache[MaxCacheSize];
                    }

                    // check the existing constraints from previous calls
                    foreach (PreferredSizeCache sizeCache in _sizeCacheList)
                    {
                        if (sizeCache.ConstrainingSize == proposedConstraints)
                        {
                            return(sizeCache.PreferredSize);
                        }
                        else if ((sizeCache.ConstrainingSize.Width == proposedConstraints.Width) &&
                                 (sizeCache.PreferredSize.Height <= proposedConstraints.Height))
                        {
                            // Caching a common case where the width matches perfectly, and the stored preferred height
                            // is smaller or equal to the constraining size.
                            //        prefSize = GetPreferredSize(w,Int32.MaxValue);
                            //        prefSize = GetPreferredSize(w,prefSize.Height);

                            return(sizeCache.PreferredSize);
                        }

                        //
                    }

                    // if we've gotten here, it means we don't have a cache entry, therefore
                    // we should add a new one in the next available slot.
                    Size prefSize = TextRenderer.MeasureText(text, font, proposedConstraints, flags);
                    _nextCacheEntry = (_nextCacheEntry + 1) % MaxCacheSize;
                    _sizeCacheList[_nextCacheEntry] = new PreferredSizeCache(proposedConstraints, prefSize);

                    return(prefSize);
                }
            }
Example #41
0
 public static Size MeasureText(string text, Font font, Size proposedSize, TextFormatFlags flags)
 {
     return(MeasureTextInternal(Hwnd.GraphicsContext, text, font, proposedSize, flags, false));
 }
 ///  TextRequiresWordBreak
 ///  If you give the text all the space in the world it wants, then there should be no reason
 ///  for it to break on a word.  So we find out what the unconstrained size is (Int32.MaxValue, Int32.MaxValue)
 ///  for a string - eg. 35, 13.  If the size passed in has a larger width than 35, then we know that
 ///  the WordBreak flag is not necessary.
 public bool TextRequiresWordBreak(string?text, Font?font, Size size, TextFormatFlags flags)
 {
     // if the unconstrained size of the string is larger than the proposed width
     // we need the word break flag, otherwise we don't, its a perf hit to use it.
     return(GetUnconstrainedSize(text, font, flags).Width > size.Width);
 }
        private static TextFormatFlags StringFormatToFlags(StringFormat sf)
        {
            TextFormatFlags flags = new TextFormatFlags();

            // Translation table: http://msdn.microsoft.com/msdnmag/issues/06/03/TextRendering/default.aspx?fig=true#fig4

            switch (sf.Alignment)
            {
            // Horizontal Alignment
            case StringAlignment.Center:
                flags = flags & TextFormatFlags.HorizontalCenter;
                break;

            case StringAlignment.Far:
                flags = flags & TextFormatFlags.Right;
                break;

            default:
                flags = flags & TextFormatFlags.Left;
                break;
            }

            switch (sf.LineAlignment)
            {
            // Vertical Alignment
            case StringAlignment.Far:
                flags = flags & TextFormatFlags.Bottom;
                break;

            case StringAlignment.Center:
                flags = flags & TextFormatFlags.VerticalCenter;
                break;

            default:
                flags = flags & TextFormatFlags.Top;
                break;
            }

            switch (sf.Trimming)
            {
            // Ellipsis
            case StringTrimming.EllipsisCharacter:
                flags = flags & TextFormatFlags.EndEllipsis;
                break;

            case StringTrimming.EllipsisPath:
                flags = flags & TextFormatFlags.PathEllipsis;
                break;

            case StringTrimming.EllipsisWord:
                flags = flags & TextFormatFlags.WordEllipsis;
                break;
            }

            // Hotkey Prefix
            if (sf.HotkeyPrefix == HotkeyPrefix.None)
            {
                flags = flags & TextFormatFlags.NoPrefix;
            }
            else if (sf.HotkeyPrefix == HotkeyPrefix.Hide)
            {
                flags = flags & TextFormatFlags.HidePrefix;
            }

            // Text Padding
            if (sf.FormatFlags == StringFormatFlags.FitBlackBox)
            {
                flags = flags & TextFormatFlags.NoPadding;
            }

            // Text Wrapping
            if (sf.FormatFlags == StringFormatFlags.NoWrap)
            {
                flags = flags & TextFormatFlags.SingleLine;
            }
            else if (sf.FormatFlags == StringFormatFlags.LineLimit)
            {
                flags = flags & TextFormatFlags.TextBoxControl;
            }

            // Other Flags
            if (sf.FormatFlags == StringFormatFlags.DirectionRightToLeft)
            {
                flags = flags & TextFormatFlags.RightToLeft;
            }

            if (sf.FormatFlags == StringFormatFlags.NoClip)
            {
                flags = flags & TextFormatFlags.NoClipping;
            }

            return(flags);
        }
        private static StringFormat FlagsToStringFormat(TextFormatFlags flags)
        {
            StringFormat sf = new StringFormat();

            // Translation table: http://msdn.microsoft.com/msdnmag/issues/06/03/TextRendering/default.aspx?fig=true#fig4

            // Horizontal Alignment
            if ((flags & TextFormatFlags.HorizontalCenter) == TextFormatFlags.HorizontalCenter)
            {
                sf.Alignment = StringAlignment.Center;
            }
            else if ((flags & TextFormatFlags.Right) == TextFormatFlags.Right)
            {
                sf.Alignment = StringAlignment.Far;
            }
            else
            {
                sf.Alignment = StringAlignment.Near;
            }

            // Vertical Alignment
            if ((flags & TextFormatFlags.Bottom) == TextFormatFlags.Bottom)
            {
                sf.LineAlignment = StringAlignment.Far;
            }
            else if ((flags & TextFormatFlags.VerticalCenter) == TextFormatFlags.VerticalCenter)
            {
                sf.LineAlignment = StringAlignment.Center;
            }
            else
            {
                sf.LineAlignment = StringAlignment.Near;
            }

            // Ellipsis
            if ((flags & TextFormatFlags.EndEllipsis) == TextFormatFlags.EndEllipsis)
            {
                sf.Trimming = StringTrimming.EllipsisCharacter;
            }
            else if ((flags & TextFormatFlags.PathEllipsis) == TextFormatFlags.PathEllipsis)
            {
                sf.Trimming = StringTrimming.EllipsisPath;
            }
            else if ((flags & TextFormatFlags.WordEllipsis) == TextFormatFlags.WordEllipsis)
            {
                sf.Trimming = StringTrimming.EllipsisWord;
            }
            else
            {
                sf.Trimming = StringTrimming.Character;
            }

            // Hotkey Prefix
            if ((flags & TextFormatFlags.NoPrefix) == TextFormatFlags.NoPrefix)
            {
                sf.HotkeyPrefix = HotkeyPrefix.None;
            }
            else if ((flags & TextFormatFlags.HidePrefix) == TextFormatFlags.HidePrefix)
            {
                sf.HotkeyPrefix = HotkeyPrefix.Hide;
            }
            else
            {
                sf.HotkeyPrefix = HotkeyPrefix.Show;
            }

            // Text Padding
            if ((flags & TextFormatFlags.NoPadding) == TextFormatFlags.NoPadding)
            {
                sf.FormatFlags |= StringFormatFlags.FitBlackBox;
            }

            // Text Wrapping
            if ((flags & TextFormatFlags.SingleLine) == TextFormatFlags.SingleLine)
            {
                sf.FormatFlags |= StringFormatFlags.NoWrap;
            }
            else if ((flags & TextFormatFlags.TextBoxControl) == TextFormatFlags.TextBoxControl)
            {
                sf.FormatFlags |= StringFormatFlags.LineLimit;
            }

            // Other Flags
            //if ((flags & TextFormatFlags.RightToLeft) == TextFormatFlags.RightToLeft)
            //        sf.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
            if ((flags & TextFormatFlags.NoClipping) == TextFormatFlags.NoClipping)
            {
                sf.FormatFlags |= StringFormatFlags.NoClip;
            }

            return(sf);
        }
Example #45
0
 public abstract void CPDrawStringDisabled(IDeviceContext dc, string s, Font font, Color_ color, Rectangle_ layoutRectangle, TextFormatFlags format);
Example #46
0
        public CGlyph(char chr, float MaxHigh)
        {
            _SIZEh = MaxHigh;

            float           outline = CFonts.Outline;
            TextFormatFlags flags   = TextFormatFlags.NoPadding | TextFormatFlags.NoPrefix;

            float factor = GetFactor(chr, flags);

            CFonts.Height = SIZEh * factor;
            Bitmap bmp = new Bitmap(10, 10);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);

            Font fo    = CFonts.GetFont();
            Size sizeB = TextRenderer.MeasureText(g, chr.ToString(), fo, new Size(int.MaxValue, int.MaxValue), flags);

            SizeF size = g.MeasureString(chr.ToString(), fo);

            g.Dispose();
            bmp.Dispose();

            bmp = new Bitmap((int)(sizeB.Width * 2f), sizeB.Height);
            g   = System.Drawing.Graphics.FromImage(bmp);
            g.Clear(System.Drawing.Color.Transparent);

            g.SmoothingMode     = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            CFonts.Height       = SIZEh;
            fo = CFonts.GetFont();

            PointF point = new PointF(
                outline * Math.Abs(sizeB.Width - size.Width) + (sizeB.Width - size.Width) / 2f + SIZEh / 5f,
                (sizeB.Height - size.Height - (size.Height + SIZEh / 4f) * (1f - factor)) / 2f);

            GraphicsPath path = new GraphicsPath();

            path.AddString(
                chr.ToString(),
                fo.FontFamily,
                (int)fo.Style,
                SIZEh,
                point,
                new StringFormat());

            Pen pen = new Pen(
                Color.FromArgb(
                    (int)CFonts.OutlineColor.A * 255,
                    (int)CFonts.OutlineColor.R * 255,
                    (int)CFonts.OutlineColor.G * 255,
                    (int)CFonts.OutlineColor.B * 255),
                SIZEh * outline);

            pen.LineJoin = LineJoin.Round;
            g.DrawPath(pen, path);
            g.FillPath(Brushes.White, path);

            /*
             * g.DrawString(
             *  chr.ToString(),
             *  fo,
             *  Brushes.White,
             *  point);
             * */

            Texture = CDraw.AddTexture(bmp);
            //bmp.Save("test.png", ImageFormat.Png);
            Chr   = chr;
            width = (int)((1f + outline / 2f) * sizeB.Width * Texture.width / factor / bmp.Width);

            bmp.Dispose();
            g.Dispose();
            fo.Dispose();
        }
Example #47
0
        private void PaintTab(Graphics g, Tab t, int index, bool selected)
        {
            PointPath path = GetTabPath(index);

            Color tabColor = selected ? this.Owner.SelectedTabColor : this.Owner.TabColor;

            if ((!selected || this.Owner.ShowHitTest) &&
                this.Owner.Focused &&
                path.HitTest(this.Owner.PointToClient(Control.MousePosition)))
            {
                if (this.Owner.ShowHitTest)
                {
                    tabColor = Color.LightBlue;
                }
                else
                {
                    tabColor = ControlPaint.Light(tabColor, 0.60f);
                }
            }

            using (Brush b = new SolidBrush(tabColor))
            {
                g.FillPointPath(b, path);
                using Pen bp = new Pen(b);
                g.DrawPointPath(bp, path, true);
            }

            using (Pen p = new Pen(this.Owner.TabBorderColor))
            {
                g.DrawPointPath(p, path, false);
            }

            int textAreaWidth = path.MinimumBounds.Width - 2 * TAB_CLOSE_BUTTON_RADIUS - TAB_CLOSE_BUTTON_PADDING;
            int textAreaX     = path.MinimumBounds.X;

            if (t.Icon != null)
            {
                int x = path.MinimumBounds.Left + TAB_ICON_PADDING;
                int y = path.MinimumBounds.Top + (path.MinimumBounds.Height - TAB_ICON_SIZE) / 2;
                g.DrawImage(t.Icon, new Rectangle(x, y, TAB_ICON_SIZE, TAB_ICON_SIZE));
                textAreaWidth -= TAB_ICON_SIZE + 2 * TAB_ICON_PADDING;
                textAreaX     += TAB_ICON_SIZE + 2 * TAB_ICON_PADDING;
            }

            Rectangle       bounds = new Rectangle(textAreaX, path.MinimumBounds.Y, textAreaWidth, path.MinimumBounds.Height);
            TextFormatFlags flags  = TextFormatFlags.HorizontalCenter
                                     | TextFormatFlags.VerticalCenter
                                     | TextFormatFlags.SingleLine
                                     | TextFormatFlags.LeftAndRightPadding;

            if (t.Text.Contains(Path.DirectorySeparatorChar) ||
                t.Text.Contains(Path.AltDirectorySeparatorChar))
            {
                flags |= TextFormatFlags.PathEllipsis;
            }
            else
            {
                flags |= TextFormatFlags.WordEllipsis;
            }
            TextRenderer.DrawText(g, t.Text, t.Font, bounds, t.ForeColor, flags);

            PaintTabClose(g, index);
        }
Example #48
0
 public void ShowAccellerator()
 {
     this.tff         = tffShowPrefix;
     this.UseMnemonic = true;
     this.Invalidate();
 }
Example #49
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="alignment"></param>
        /// <param name="rightToleft"></param>
        /// <returns></returns>
        internal static TextFormatFlags GetTextFormatFlags(ContentAlignment alignment, bool rightToleft)
        {
            TextFormatFlags textFormatFlags = TextFormatFlags.SingleLine | TextFormatFlags.WordBreak;

            if (rightToleft)
            {
                textFormatFlags |= (TextFormatFlags.Right | TextFormatFlags.RightToLeft);
            }
            if (alignment <= ContentAlignment.MiddleCenter)
            {
                switch (alignment)
                {
                case ContentAlignment.TopLeft:
                    //textFormatFlags = textFormatFlags;
                    break;

                case ContentAlignment.TopCenter:
                    textFormatFlags |= TextFormatFlags.HorizontalCenter;
                    break;

                case (ContentAlignment.TopLeft | ContentAlignment.TopCenter):
                    break;

                case ContentAlignment.TopRight:
                    textFormatFlags |= TextFormatFlags.Right;
                    break;

                default:
                    if (alignment != ContentAlignment.MiddleLeft)
                    {
                        if (alignment == ContentAlignment.MiddleCenter)
                        {
                            textFormatFlags |= (TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
                        }
                    }
                    else
                    {
                        textFormatFlags |= TextFormatFlags.VerticalCenter;
                    }
                    break;
                }
            }
            else
            {
                if (alignment <= ContentAlignment.BottomLeft)
                {
                    if (alignment != ContentAlignment.MiddleRight)
                    {
                        if (alignment == ContentAlignment.BottomLeft)
                        {
                            textFormatFlags |= TextFormatFlags.Bottom;
                        }
                    }
                    else
                    {
                        textFormatFlags |= (TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
                    }
                }
                else
                {
                    if (alignment != ContentAlignment.BottomCenter)
                    {
                        if (alignment == ContentAlignment.BottomRight)
                        {
                            textFormatFlags |= (TextFormatFlags.Bottom | TextFormatFlags.Right);
                        }
                    }
                    else
                    {
                        textFormatFlags |= (TextFormatFlags.Bottom | TextFormatFlags.HorizontalCenter);
                    }
                }
            }
            return(textFormatFlags);
        }
Example #50
0
 private static void DrawText(Graphics g, Rectangle bounds, string text, Font font, Color foreColor, TextFormatFlags flags)
 {
     TextRenderer.DrawText(g, text, font, bounds, foreColor, flags);
 }
Example #51
0
 /// <summary>
 ///  Provides the size, in pixels, of the specified text when drawn with the specified font and formatting
 ///  instructions, using the specified size to create the initial bounding rectangle for the text.
 /// </summary>
 /// <param name="text">The text to measure.</param>
 /// <param name="font">The <see cref="Font"/> to apply to the measured text.</param>
 /// <param name="proposedSize">The <see cref="Size"/> of the initial bounding rectangle.</param>
 /// <param name="flags">The formatting instructions to apply to the measured text.</param>
 /// <returns>
 ///  The <see cref="Size"/>, in pixels, of <paramref name="text"/> drawn with the specified
 ///  <paramref name="font"/> and format.
 /// </returns>
 /// <exception cref="ArgumentOutOfRangeException">
 ///  Thrown if <see cref="TextFormatFlags.ModifyString"/> is set.
 /// </exception>
 public static Size MeasureText(ReadOnlySpan <char> text, Font?font, Size proposedSize, TextFormatFlags flags)
 => MeasureTextInternal(text, font, proposedSize, BlockModifyString(flags));
Example #52
0
        //private static IntPtr SmallImageListHandle;
        //private static IntPtr LargeImageListHandle;
        //SHFILEINFO shFileInfo = new SHFILEINFO();
        public UserControl1()
        {
            InitializeComponent();

            ChangedItems = new List <string>();
            iconcache    = new ImageList();

            //this.DoubleBuffered = true;
            this.Margin = new Padding(0);

            //textBox1.Enter += (s, e) => {
            //    textBox1.SelectAll();
            //};
            //textBox1.MouseDown += (s, e) => {
            //    if (textBox1.SelectionLength == 0) {
            //        textBox1.SelectAll();
            //    }
            //};

            listView1      = new ListViewEx();
            listView1.Dock = DockStyle.Fill;
            panel2.Controls.Add(listView1);

            listView1.View            = View.Details;
            listView1.OwnerDraw       = true;
            listView1.VirtualMode     = true;
            listView1.VirtualListSize = 0;
            //listView1.FullRowSelect = true;
            //listView1.View = View.Details;
            listView1.ShowItemToolTips = true;


            listView1.SmallImageList = new ImageList();
            //listView1.StateImageList = imageList1;
            //listView1.LargeImageList = new ImageList();
            //listView1.SmallImageList.ColorDepth = ColorDepth.Depth32Bit;
            listView1.SmallImageList.ImageSize = new Size(16, 16);
            //SHFILEINFO shFileInfo = new SHFILEINFO();
            //SmallImageListHandle = NativeMethods.SHGetFileInfo(String.Empty, 0,
            //    out shFileInfo, (uint)Marshal.SizeOf(shFileInfo),
            //    NativeMethods.SHGFI_SMALLICON | NativeMethods.SHGFI_SYSICONINDEX);
            //LargeImageListHandle = NativeMethods.SHGetFileInfo(String.Empty, 0,
            //    out shFileInfo, (uint)Marshal.SizeOf(shFileInfo),
            //    NativeMethods.SHGFI_LARGEICON | NativeMethods.SHGFI_SYSICONINDEX);
            //NativeMethods.SendMessage(listView1.Handle, NativeMethods.LVM_SETIMAGELIST,
            //    new IntPtr(NativeMethods.LVSIL_SMALL), SmallImageListHandle);
            //NativeMethods.SendMessage(listView1.Handle, NativeMethods.LVM_SETIMAGELIST,
            //    new IntPtr(NativeMethods.LVSIL_NORMAL), LargeImageListHandle);


            this.sortcolum = 0;
            this.type      = SortType.Name;
            this.sortOrder = 1;

            //hwnd_ = listView1.Handle;
            //dc_ = Win32API.GetDC(hwnd_);
            //hfont_ = listView1.Font.ToHfont();
            headerBrush = new SolidBrush(Color.DarkGray);

            //int styles = (int)MF.Win32API.NativeMethods.SendMessage(listView1.Handle, (int)LVM_GETEXTENDEDLISTVIEWSTYLE, 0, (IntPtr)0);
            //styles |= LVS_EX_DOUBLEBUFFER;
            //MF.Win32API.NativeMethods.SendMessage(listView1.Handle, (int)LVM_SETEXTENDEDLISTVIEWSTYLE, 0, (IntPtr)styles);

            //DateWidth = GetTextExtend(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")).width+10;
            //DateTimeColumWidth = GetTextExtend(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")).width + 10;
            //Win32API.ReleaseDC(hwnd_, dc_);
            //Win32API.DeleteObject(hfont_);
            DateTimeColumWidth = Util.GetTextExtend(listView, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")).width + 10;

            ColumnHeader headerName = new ColumnHeader();

            headerName.Name = "name";
            headerName.Text = "name";
            listView1.Columns.Add(headerName);

            ColumnHeader headerType = new ColumnHeader();

            headerType.Name = "type";
            headerType.Text = "type";
            listView1.Columns.Add(headerType);

            ColumnHeader headerSize = new ColumnHeader();

            headerSize.Name = "size";
            headerSize.Text = "size";
            listView1.Columns.Add(headerSize);

            ColumnHeader headerLastWriteTime = new ColumnHeader();

            headerLastWriteTime.Name  = "lastwritetime";
            headerLastWriteTime.Text  = "lastwritetime";
            headerLastWriteTime.Width = DateTimeColumWidth;

            //headerLastWriteTime.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
            listView1.Columns.Add(headerLastWriteTime);



            listView1.RetrieveVirtualItem += (sender, e) => {
                if (e.ItemIndex < Items.Count)
                {
                    var item         = Items[e.ItemIndex];
                    var listviewitem = new ListViewItem();
                    listviewitem.Text = item.Name;
                    //if (item.IsFile) {
                    //listviewitem.ForeColor = Color.Yellow;
                    listviewitem.SubItems.Add(item.type);
                    //}
                    //else {
                    //    listviewitem.SubItems.Add("Dir");
                    //}
                    //    listviewitem.ImageIndex = 0;
                    listviewitem.SubItems.Add(getFileSizeFormat(item.Size));
                    if (item.LastWriteTime != null)
                    {
                        listviewitem.SubItems.Add(item.LastWriteTime.ToString("yyyy/MM/dd HH:mm:ss"));
                    }

                    if (item.type == ".exe")
                    {
                        if (!iconcache.Images.ContainsKey(item.Name))
                        {
                            Image icon;
                            if (IconMethods.getIcon(Path.Combine(this.Dir, item.Name), out icon))
                            {
                                iconcache.Images.Add(item.Name, icon);
                            }
                        }
                    }
                    //listviewitem.SubItems.Add(item.LastWriteTime.ToLongDateString());
                    e.Item = listviewitem;

                    //                NativeMethods.SHGetFileInfo(Path.Combine(this.Dir, item.Name), 0, out shFileInfo,
                    //(uint)Marshal.SizeOf(shFileInfo), NativeMethods.SHGFI_ICON |
                    //NativeMethods.SHGFI_SYSICONINDEX | NativeMethods.SHGFI_OVERLAYINDEX);
                    //                // 最上位8ビットを除いた値をアイコンインデックス値とする
                    //                int iconIndex = (shFileInfo.iIcon & 0xFFFFFF);
                    //                listviewitem.ImageIndex = iconIndex;
                    //                LVITEM lvitem = new LVITEM();
                    //                lvitem.stateMask = NativeMethods.LVIS_OVERLAYMASK;
                    //                // 最上位8ビットの値を、8-11ビット目に格納、それ以外のビットは 0 にする
                    //                lvitem.state = ((shFileInfo.iIcon >> 16) & 0x0F00);
                    //                NativeMethods.SendMessage(listView1.Handle,
                    //                    NativeMethods.LVM_SETITEMSTATE, listviewitem.Index, ref lvitem);
                    //                if (shFileInfo.hIcon != IntPtr.Zero)
                    //                    NativeMethods.DestroyIcon(shFileInfo.hIcon);
                }
            };

            //Brush b = new SolidBrush(Color.Red);
            listView1.DrawSubItem += (sender, e) => {
                //// 描画するSubItemが2列目(ColumnIndexが1)の時は、StringAligment.Farに設定して、右寄せにする
                //// それ以外は、Nearにして、標準の左寄せ
                //StringFormat drawFormat = new StringFormat();
                //if (e.ColumnIndex == 2) {
                //    drawFormat.Alignment = StringAlignment.Far;
                //}
                //else {
                //    drawFormat.Alignment = StringAlignment.Near;
                //}

                //System.Drawing.Brush brush;

                //// Forcus = 0x0010,Selected = 0x0001 として ItemStateにForcusとSelectedがセットされていた場合、
                //// 2bitで書くと Selected = 0001 0000 ItemState = 0000 0001で
                //// この二つ論理積を取ると0000 0001(0x0001 = Selected)となる。
                ////if ((e.ItemState & ListViewItemStates.Selected) == ListViewItemStates.Selected) {
                //if (listView1.SelectedIndices.Contains(e.ItemIndex)) {
                //    // Hightlightで範囲を塗りつぶす
                //    if (e.ColumnIndex == 0) {

                //        e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);

                //    // 上でセルを塗りつぶしているので、表示する文字を反転する
                //    brush = SystemBrushes.HighlightText;
                //    }else{
                //        brush = SystemBrushes.WindowText;
                //    }
                //}
                //else {
                //    //if (!Items[e.ItemIndex].IsFile) {
                //    //    brush = SystemBrushes.HighlightText;
                //    //} else {
                //    // 塗りつぶされていない通常のセルはWindowsTextに設定する
                //    brush = SystemBrushes.WindowText;
                //    //}
                //}

                //// 上で設定した,brushとdrawFormatを利用して文字を描画する
                //e.Graphics.DrawString(e.SubItem.Text, e.Item.Font, brush, e.Bounds, drawFormat);

                //// drawFormatを開放する
                //drawFormat.Dispose();

                //TextFormatFlags flg;
                if (e.ColumnIndex == 0)
                {
                    flg = TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter;
                    //flg = TextFormatFlags.WordBreak;
                    //e.Graphics.DrawImage(imageList1.Images[0], e.Bounds.Location.X, e.Bounds.Location.Y);
                }
                else if (e.ColumnIndex == 2)
                {
                    flg = TextFormatFlags.Right;
                }
                else
                {
                    flg = TextFormatFlags.Left;
                }
                Color brush;
                if (ChangedItems.Contains(e.Item.Text))
                {
                    e.Graphics.FillRectangle(SystemBrushes.GrayText, e.Bounds);
                }
                if (e.ColumnIndex == 0 && listView1.SelectedIndices.Contains(e.ItemIndex))
                {
                    //if (e.ColumnIndex == 0) {
                    Rectangle sr = new Rectangle(e.Bounds.Location.X + 16 + 4, e.Bounds.Location.Y, listView1.Columns[e.ColumnIndex].Width - (16 + 4), e.Bounds.Height);

                    e.Graphics.FillRectangle(SystemBrushes.Highlight, sr);
                    //}
                    //Rectangle hr = new Rectangle(e.Bounds.Location, new Size(listView1.Width, e.Bounds.Height));
                    //e.Graphics.FillRectangle(SystemBrushes.Highlight, hr);
                    brush = SystemColors.HighlightText;
                }
                else
                {
                    if (Items[e.ItemIndex].IsFile)
                    {
                        brush = SystemColors.WindowText;
                    }
                    else
                    {
                        brush = Color.Blue;
                    }
                }

                if (e.ColumnIndex == 0)
                {
                    var item = Items[e.ItemIndex];
                    var img  = item.type == ".exe"?iconcache.Images[item.Name]: IconCache.Inst.getImage(Path.Combine(this.Dir, item.Name), item.type, item.IsFile);
                    if (img != null)
                    {
                        e.Graphics.DrawImage(img, e.Bounds.Location.X, e.Bounds.Location.Y, img.Width, img.Height);
                    }
                }

                //Rectangle r = new Rectangle(e.Bounds.Location, new Size(listView1.Columns[e.ColumnIndex].Width, e.Bounds.Height));
                int x = e.ColumnIndex == 0 ? e.Bounds.Location.X + 16 + 4 : e.Bounds.Location.X;
                int w = e.ColumnIndex == 0 ? listView1.Columns[e.ColumnIndex].Width - (16 + 4) : listView1.Columns[e.ColumnIndex].Width;
                //Rectangle r = new Rectangle(e.Bounds.Location.X+16+2, e.Bounds.Location.Y, listView1.Columns[e.ColumnIndex].Width, e.Bounds.Height);
                Rectangle r = new Rectangle(x, e.Bounds.Location.Y, w, e.Bounds.Height);
                TextRenderer.DrawText(e.Graphics, e.SubItem.Text, e.Item.Font, r, brush, flg);
                //e.DrawFocusRectangle(e.Item.Bounds);
                //var str = string.Join(" ", Array.ConvertAll(e.SubItem.Text.ToCharArray(),
                //delegate(Char c) { return c + "\x200c"; }));
                //TextRenderer.DrawText(e.Graphics, str, e.Item.Font, r, brush, flg);
                //e.DrawFocusRectangle(e.Item.Bounds);
            };
            //Brush b = new SolidBrush(Color.DarkGray);
            listView1.DrawColumnHeader += (sender, e) => {
                if (e.ColumnIndex == sortcolum)
                {
                    e.DrawBackground();
                    e.DrawText(TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
                    //e.Graphics.FillRectangle(b, e.Bounds.Left, e.Bounds.Top, 5, 5);
                    if (this.sortOrder == 1)
                    {
                        e.Graphics.FillPolygon(headerBrush,
                                               new Point[] { new Point(e.Bounds.Right - 10, e.Bounds.Top + 5),
                                                             new Point(e.Bounds.Right - 5, e.Bounds.Bottom - 5),
                                                             new Point(e.Bounds.Right - 15, e.Bounds.Bottom - 5) });
                    }
                    else if (this.sortOrder == -1)
                    {
                        e.Graphics.FillPolygon(headerBrush,
                                               new Point[] { new Point(e.Bounds.Right - 15, e.Bounds.Top + 5),
                                                             new Point(e.Bounds.Right - 5, e.Bounds.Top + 5),
                                                             new Point(e.Bounds.Right - 10, e.Bounds.Bottom - 5) });
                    }
                }
                else
                {
                    e.DrawDefault = true;
                }
            };

            listView1.ColumnClick += (s, e) => {
                if (this.sortcolum == e.Column)
                {
                    this.sortOrder = -1 * this.sortOrder;
                }
                else
                {
                    this.sortOrder = 1;
                }
                this.sortcolum = e.Column;

                //listView.Invalidate(new Rectangle(0, 0, listView.Width, listView.Height-listView.ClientSize.Height), true);

                switch (e.Column)
                {
                case 0:
                    this.sort(SortType.Name, this.sortOrder);
                    break;

                case 1:
                    this.sort(SortType.Type, this.sortOrder);
                    break;

                case 2:
                    this.sort(SortType.Size, this.sortOrder);
                    break;

                case 3:
                    this.sort(SortType.WriteTime, this.sortOrder);
                    break;

                default:
                    break;
                }
            };
            //bool res = false;

            listView1.MouseDown += (s, e) => {
                var lv = s as ListView;
                if (e.Button == MouseButtons.Middle || e.Button == MouseButtons.Right)
                {
                    var item = lv.GetItemAt(e.Location.X, e.Location.Y);
                    if (item != null)
                    {
                        if ((e.Button == MouseButtons.Right && !lv.SelectedIndices.Contains(item.Index)) ||
                            e.Button == MouseButtons.Middle)
                        {
                            var indexs = new int[lv.SelectedIndices.Count];
                            lv.SelectedIndices.CopyTo(indexs, 0);
                            for (int i = 0; i < indexs.Length; i++)
                            {
                                listView1.Items[indexs[i]].Selected = false;
                            }
                            item.Selected = true;
                        }
                    }
                }
            };

            textBox1.KeyDown += (sender, e) => {
                if (e.KeyCode == Keys.Return)
                {
                    Dir = textBox1.Text;
                }
            };

            CloseLabel.Click += (s, e) => {
                Close();
            };

            fileSystemWatcher1.IncludeSubdirectories = false;
            //fileSystemWatcher1.NotifyFilter = (NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.Size);
            fileSystemWatcher1.SynchronizingObject = this;
            fileSystemWatcher1.Created            += new FileSystemEventHandler(fileSystemWatcher1_Changed);
            fileSystemWatcher1.Deleted            += new FileSystemEventHandler(fileSystemWatcher1_Changed);
            fileSystemWatcher1.Changed            += new FileSystemEventHandler(fileSystemWatcher1_Changed);
            fileSystemWatcher1.Renamed            += (s, e) => {
                //var index = e.OldFullPath.LastIndexOf("\\");
                //var oldname = e.OldFullPath.Substring(index + 1, e.OldFullPath.Length - (index + 1));
                var old = Items.First(x => {
                    return(x.Name.Equals(e.OldName));
                });
                if (old != null)
                {
                    old.Name = e.Name;
                    var index = Items.IndexOf(old);
                    listView1.RedrawItems(index, index, false);
                }
            };
        }
        private Rectangle GetAdjustedEditingControlBounds(Rectangle editingControlBounds, DataGridViewCellStyle cellStyle)
        {
            Debug.Assert(cellStyle.WrapMode != DataGridViewTriState.NotSet);
            Debug.Assert(this.DataGridView != null);

            TextBox txtEditingControl = this.DataGridView.EditingControl as TextBox;
            int     originalWidth     = editingControlBounds.Width;

            if (txtEditingControl != null)
            {
                switch (cellStyle.Alignment)
                {
                case DataGridViewContentAlignment.TopLeft:
                case DataGridViewContentAlignment.MiddleLeft:
                case DataGridViewContentAlignment.BottomLeft:
                    // Add 3 pixels on the left of the editing control to match non-editing text position
                    if (this.DataGridView.RightToLeftInternal)
                    {
                        editingControlBounds.X    += 1;
                        editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft - 2);
                    }
                    else
                    {
                        editingControlBounds.X    += DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft;
                        editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetLeft - 1);
                    }
                    break;

                case DataGridViewContentAlignment.TopCenter:
                case DataGridViewContentAlignment.MiddleCenter:
                case DataGridViewContentAlignment.BottomCenter:
                    editingControlBounds.X    += 1;
                    editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - 3);
                    break;

                case DataGridViewContentAlignment.TopRight:
                case DataGridViewContentAlignment.MiddleRight:
                case DataGridViewContentAlignment.BottomRight:
                    // Shorten the editing control by 5 pixels to match non-editing text position
                    if (this.DataGridView.RightToLeftInternal)
                    {
                        editingControlBounds.X    += DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight - 1;
                        editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight);
                    }
                    else
                    {
                        editingControlBounds.X    += 1;
                        editingControlBounds.Width = Math.Max(0, editingControlBounds.Width - DATAGRIDVIEWTEXTBOXCELL_horizontalTextOffsetRight - 1);
                    }
                    break;
                }

                switch (cellStyle.Alignment)
                {
                case DataGridViewContentAlignment.TopLeft:
                case DataGridViewContentAlignment.TopCenter:
                case DataGridViewContentAlignment.TopRight:
                    editingControlBounds.Y     += DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetTop;
                    editingControlBounds.Height = Math.Max(0, editingControlBounds.Height - DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetTop);
                    break;

                case DataGridViewContentAlignment.MiddleLeft:
                case DataGridViewContentAlignment.MiddleCenter:
                case DataGridViewContentAlignment.MiddleRight:
                    editingControlBounds.Height++;
                    break;

                case DataGridViewContentAlignment.BottomLeft:
                case DataGridViewContentAlignment.BottomCenter:
                case DataGridViewContentAlignment.BottomRight:
                    editingControlBounds.Height = Math.Max(0, editingControlBounds.Height - DATAGRIDVIEWTEXTBOXCELL_verticalTextOffsetBottom);
                    break;
                }

                int preferredHeight;
                if (cellStyle.WrapMode == DataGridViewTriState.False)
                {
                    preferredHeight = txtEditingControl.PreferredSize.Height;
                }
                else
                {
                    string editedFormattedValue = (string)((IDataGridViewEditingControl)txtEditingControl).GetEditingControlFormattedValue(DataGridViewDataErrorContexts.Formatting);
                    if (string.IsNullOrEmpty(editedFormattedValue))
                    {
                        editedFormattedValue = " ";
                    }
                    TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
                    using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics())
                    {
                        preferredHeight = DataGridViewCell.MeasureTextHeight(g, editedFormattedValue, cellStyle.Font, originalWidth, flags);
                    }
                }
                if (preferredHeight < editingControlBounds.Height)
                {
                    switch (cellStyle.Alignment)
                    {
                    case DataGridViewContentAlignment.TopLeft:
                    case DataGridViewContentAlignment.TopCenter:
                    case DataGridViewContentAlignment.TopRight:
                        // Single pixel move - leave it as is for now
                        break;

                    case DataGridViewContentAlignment.MiddleLeft:
                    case DataGridViewContentAlignment.MiddleCenter:
                    case DataGridViewContentAlignment.MiddleRight:
                        editingControlBounds.Y += (editingControlBounds.Height - preferredHeight) / 2;
                        break;

                    case DataGridViewContentAlignment.BottomLeft:
                    case DataGridViewContentAlignment.BottomCenter:
                    case DataGridViewContentAlignment.BottomRight:
                        editingControlBounds.Y += editingControlBounds.Height - preferredHeight;
                        break;
                    }
                }
            }

            return(editingControlBounds);
        }
        public int UxThemeDrawThemeText(IntPtr hTheme, IDeviceContext dc, int iPartId, int iStateId, string text, TextFormatFlags textFlags, Rectangle bounds)
        {
            XplatUIWin32.RECT BoundsRect = XplatUIWin32.RECT.FromRectangle(bounds);

            int result = UXTheme.DrawThemeText(hTheme, dc.GetHdc(), iPartId, iStateId, text, text.Length, (uint)textFlags, 0, ref BoundsRect);

            dc.ReleaseHdc();
            return(result);
        }
Example #55
0
 public static Size MeasureText(string?text, Font?font, Size proposedSize, TextFormatFlags flags)
 => MeasureTextInternal(text, font, proposedSize, flags);
        protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e)
        {
            switch (DrawMode)
            {
            case drawMode.Default:
                base.OnDrawSubItem(e);

                break;

            case drawMode.Stylish:
                base.OnDrawSubItem(e);

                Graphics g = e.Graphics;
                g.SmoothingMode     = Smoothing;
                g.TextRenderingHint = TextRendering;

                TextFormatFlags flags = TextFormatFlags.Left;

                using (StringFormat sf = new StringFormat())
                {
                    // Store the column text alignment, letting it default
                    // to Left if it has not been set to Center or Right.
                    switch (e.Header.TextAlign)
                    {
                    case HorizontalAlignment.Center:
                        sf.Alignment = StringAlignment.Center;
                        flags        = TextFormatFlags.HorizontalCenter;
                        break;

                    case HorizontalAlignment.Right:
                        sf.Alignment = StringAlignment.Far;
                        flags        = TextFormatFlags.Right;
                        break;
                    }

                    // Draw the text and background for a subitem with a
                    // negative value.
                    double subItemValue;
                    if (e.ColumnIndex > 0 && Double.TryParse(
                            e.SubItem.Text, NumberStyles,
                            NumberFormatInfo.CurrentInfo, out subItemValue) &&
                        subItemValue < 0)
                    {
                        // Unless the item is selected, draw the standard
                        // background to make it stand out from the gradient.
                        if ((e.ItemState & ListViewItemStates.Selected) == 0)
                        {
                            e.DrawBackground();
                        }

                        // Draw the subitem text in red to highlight it.
                        g.DrawString(e.SubItem.Text,
                                     Font, new SolidBrush(SubTextColor), e.Bounds, sf);

                        return;
                    }

                    if (ShowCellBorder)
                    {
                        foreach (var items in Items)
                        {
                            e.Graphics.DrawRectangle(CellBorderFocused.GetPen(), new Rectangle(e.Bounds.X + (int)HeaderBorder.GetPen().Width, e.Bounds.Y + (int)HeaderBorder.GetPen().Width, e.Bounds.Width - (2 * (int)HeaderBorder.GetPen().Width), e.Bounds.Height - (2 * (int)HeaderBorder.GetPen().Width)));
                        }
                    }

                    // Draw normal text for a subitem with a nonnegative
                    // or nonnumerical value.
                    e.DrawText(flags);
                }
                break;
            }
        }
 public static Size Measure(string text, Font font, TextFormatFlags flags)
 {
     return(TextRenderer.MeasureText(text, font, MaxSize, flags));
 }
 public void Print(string text, Font font, Color color, Rectangle box, TextFormatFlags flags)
 {
     textItems.Add(new TextItem(text, font, color, box, flags));
 }
Example #59
0
 public CalendarRendererBoxEventArgs(CalendarRendererEventArgs original, Rectangle bounds, string text, Color textColour, TextFormatFlags flags)
     : this(original)
 {
     Bounds     = bounds;
     Text       = text;
     TextColour = TextColour;
     Format    |= flags;
 }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Handles the CellPainting event of the dataGridView1 control.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
        {
            base.OnCellPainting(e);

            if (e.Handled || e.RowIndex < 0 || e.ColumnIndex < 0 || m_list == null ||
                m_list.Count == 0 || m_list[e.RowIndex] == null)
            {
                return;
            }

            e.Handled = true;

            // Paint everything but the focus rectangle, foreground and background.
            // I'm not sure what's left, but just in case...
            DataGridViewPaintParts parts = e.PaintParts;

            parts &= ~DataGridViewPaintParts.Focus;
            parts &= ~DataGridViewPaintParts.Background;
            parts &= ~DataGridViewPaintParts.ContentForeground;
            e.Paint(e.CellBounds, parts);
            e.PaintBackground(e.CellBounds, false);

            IInspectorObject io             = m_list[e.RowIndex];
            Rectangle        rcText         = e.CellBounds;
            Rectangle        rcHotSpot      = Rectangle.Empty;
            bool             isSelected     = ((e.State & DataGridViewElementStates.Selected) > 0);
            bool             isInBlock      = (!isSelected && e.RowIndex >= m_firstRowInShadind && e.RowIndex <= m_lastRowInShading);
            bool             isIndentedCell = (e.ColumnIndex == 0);

            if (isIndentedCell)
            {
                // Calculate the location and size of the rectangle into which text will be drawn.
                // Adjust the text rectangle to account for the +/- image and the proper indent level.
                rcHotSpot = GetExpandCollapseRect(e.CellBounds, io.Level);
                int dx = ((rcHotSpot.Right - rcText.X) + 5);
                rcText.X     += dx;
                rcText.Width -= dx;
            }

            // Draw the background color for the cell.
            using (SolidBrush br = new SolidBrush(DefaultCellStyle.BackColor))
            {
                if (isSelected)
                {
                    br.Color = DefaultCellStyle.SelectionBackColor;
                }
                else if (isInBlock && m_clrShading != Color.Empty)
                {
                    br.Color = m_clrShading;
                }

                e.Graphics.FillRectangle(br, rcText);
            }

            Color           clrFore = (isSelected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor);
            TextFormatFlags flags   = TextFormatFlags.Left | TextFormatFlags.VerticalCenter |
                                      TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine;

            TextRenderer.DrawText(e.Graphics, e.FormattedValue as string,
                                  e.CellStyle.Font, rcText, clrFore, flags);

            DrawBorders(e, isIndentedCell,
                        (isInBlock && m_clrShading != Color.Empty ? m_clrShading : GridColor),
                        (isInBlock ? rcText.X: rcHotSpot.X));

            if (!isIndentedCell)
            {
                return;
            }

            DrawTreeLines(e, rcHotSpot, io.Level);

            if (io.HasChildren)
            {
                // Draw the expand or collapse (+/-) image.
                e.Graphics.DrawImage(m_list.IsExpanded(e.RowIndex) ?
                                     Properties.Resources.kimidCollapse : Properties.Resources.kimidExpand, rcHotSpot);
            }
        }