Exemplo n.º 1
0
        [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")]     // using "\t" to figure out the width of tab
        private void  CalculateInternalLayoutMetrics()
        {
            Size maxTextSize        = Size.Empty;
            Size maxImageSize       = Size.Empty;
            Size maxCheckSize       = scaledDefaultImageSize;
            Size maxArrowSize       = Size.Empty;
            Size maxNonMenuItemSize = Size.Empty;

            // determine Text Metrics
            for (int i = 0; i < Items.Count; i++)
            {
                ToolStripItem     item     = Items[i];
                ToolStripMenuItem menuItem = item as ToolStripMenuItem;

                if (menuItem != null)
                {
                    Size menuItemTextSize = menuItem.GetTextSize();

                    if (menuItem.ShowShortcutKeys)
                    {
                        Size shortcutTextSize = menuItem.GetShortcutTextSize();
                        if (tabWidth == -1)
                        {
                            tabWidth = TextRenderer.MeasureText("\t", this.Font).Width;
                        }
                        menuItemTextSize.Width += tabWidth + shortcutTextSize.Width;
                        menuItemTextSize.Height = Math.Max(menuItemTextSize.Height, shortcutTextSize.Height);
                    }

                    // we truly only care about the maximum size we find.
                    maxTextSize.Width  = Math.Max(maxTextSize.Width, menuItemTextSize.Width);
                    maxTextSize.Height = Math.Max(maxTextSize.Height, menuItemTextSize.Height);

                    // determine Image Metrics
                    Size imageSize = Size.Empty;
                    if (menuItem.Image != null)
                    {
                        imageSize = (menuItem.ImageScaling == ToolStripItemImageScaling.SizeToFit) ? ImageScalingSize : menuItem.Image.Size;
                    }

                    maxImageSize.Width  = Math.Max(maxImageSize.Width, imageSize.Width);
                    maxImageSize.Height = Math.Max(maxImageSize.Height, imageSize.Height);

                    if (menuItem.CheckedImage != null)
                    {
                        Size checkedImageSize = menuItem.CheckedImage.Size;
                        maxCheckSize.Width  = Math.Max(checkedImageSize.Width, maxCheckSize.Width);
                        maxCheckSize.Height = Math.Max(checkedImageSize.Height, maxCheckSize.Height);
                    }
                }
                else if (!(item is ToolStripSeparator))
                {
                    maxNonMenuItemSize.Height = Math.Max(item.Bounds.Height, maxNonMenuItemSize.Height);
                    maxNonMenuItemSize.Width  = Math.Max(item.Bounds.Width, maxNonMenuItemSize.Width);
                }
            }

            this.maxItemSize.Height = Math.Max(maxTextSize.Height + scaledTextPadding.Vertical, Math.Max(maxCheckSize.Height + scaledCheckPadding.Vertical, maxArrowSize.Height + scaledArrowPadding.Vertical));

            if (ShowImageMargin)
            {
                // only add in the image into the calculation if we're going to render it.
                this.maxItemSize.Height = Math.Max(maxImageSize.Height + scaledImagePadding.Vertical, maxItemSize.Height);
            }

            bool useDefaultCheckMarginWidth = (ShowCheckMargin && (maxCheckSize.Width == 0));
            bool useDefaultImageMarginWidth = (ShowImageMargin && (maxImageSize.Width == 0));

            // Always save space for an arrow
            maxArrowSize = new Size(scaledArrowSize, maxItemSize.Height);

            maxTextSize.Height  = maxItemSize.Height - scaledTextPadding.Vertical;
            maxImageSize.Height = maxItemSize.Height - scaledImagePadding.Vertical;
            maxCheckSize.Height = maxItemSize.Height - scaledCheckPadding.Vertical;

            // fixup if there are non-menu items that are larger than our normal menu items
            maxTextSize.Width = Math.Max(maxTextSize.Width, maxNonMenuItemSize.Width);

            Point nextPoint = Point.Empty;
            int   checkAndImageMarginWidth = 0;

            int extraImageWidth = Math.Max(0, maxImageSize.Width - scaledDefaultImageSize.Width);

            if (ShowCheckMargin && ShowImageMargin)
            {
                // double column - check margin then image margin
                // default to 46px - grow if necessary.
                checkAndImageMarginWidth = scaledDefaultImageAndCheckMarginWidth;

                // add in the extra space for the image... since the check size is locked down to 16x16.
                checkAndImageMarginWidth += extraImageWidth;

                // align the checkmark
                nextPoint      = new Point(scaledCheckPadding.Left, scaledCheckPadding.Top);
                checkRectangle = LayoutUtils.Align(maxCheckSize, new Rectangle(nextPoint.X, nextPoint.Y, maxCheckSize.Width, maxItemSize.Height), ContentAlignment.MiddleCenter);

                // align the image rectangle
                nextPoint.X    = checkRectangle.Right + scaledCheckPadding.Right + scaledImagePadding.Left;
                nextPoint.Y    = scaledImagePadding.Top;
                imageRectangle = LayoutUtils.Align(maxImageSize, new Rectangle(nextPoint.X, nextPoint.Y, maxImageSize.Width, maxItemSize.Height), ContentAlignment.MiddleCenter);
            }
            else if (ShowCheckMargin)
            {
                // no images should be shown in a ShowCheckMargin only scenario.
                // default to 24px - grow if necessary.
                checkAndImageMarginWidth = scaledDefaultImageMarginWidth;

                // align the checkmark
                nextPoint = new Point(1, scaledCheckPadding.Top);
                //    nextPoint = new Point(scaledCheckPadding.Left, scaledCheckPadding.Top);
                checkRectangle = LayoutUtils.Align(maxCheckSize, new Rectangle(nextPoint.X, nextPoint.Y, checkAndImageMarginWidth, maxItemSize.Height), ContentAlignment.MiddleCenter);

                imageRectangle = Rectangle.Empty;
            }
            else if (ShowImageMargin)
            {
                // checks and images render in the same area.

                // default to 24px - grow if necessary.
                checkAndImageMarginWidth = scaledDefaultImageMarginWidth;

                // add in the extra space for the image... since the check size is locked down to 16x16.
                checkAndImageMarginWidth += extraImageWidth;

                // NOTE due to the Padding property, we're going to have to recalc the vertical alignment in ToolStripMenuItemInternalLayout.
                // Dont fuss here over the Y, X is what's critical.

                // check and image rect are the same - take the max of the image size and the check size and align
                nextPoint      = new Point(1, scaledCheckPadding.Top);
                checkRectangle = LayoutUtils.Align(LayoutUtils.UnionSizes(maxCheckSize, maxImageSize), new Rectangle(nextPoint.X, nextPoint.Y, checkAndImageMarginWidth - 1, maxItemSize.Height), ContentAlignment.MiddleCenter);

                // align the image
                imageRectangle = checkRectangle;
            }
            else
            {
                checkAndImageMarginWidth = 0;
            }
            nextPoint.X = checkAndImageMarginWidth + 1;


            // calculate space for image
            // if we didnt have a check - make sure to ignore check padding

            // consider: should we constrain to a reasonable width?
            //imageMarginBounds = new Rectangle(0, 0, Math.Max(imageMarginWidth,DefaultImageMarginWidth), this.Height);
            imageMarginBounds = new Rectangle(0, 0, checkAndImageMarginWidth, this.Height);

            // calculate space for shortcut and text
            nextPoint.X   = imageMarginBounds.Right + scaledTextPadding.Left;
            nextPoint.Y   = scaledTextPadding.Top;
            textRectangle = new Rectangle(nextPoint, maxTextSize);

            // calculate space for arrow
            nextPoint.X    = textRectangle.Right + scaledTextPadding.Right + scaledArrowPadding.Left;
            nextPoint.Y    = scaledArrowPadding.Top;
            arrowRectangle = new Rectangle(nextPoint, maxArrowSize);

            // calculate space required for all of these pieces
            this.maxItemSize.Width = (arrowRectangle.Right + scaledArrowPadding.Right) - imageMarginBounds.Left;

            this.Padding = DefaultPadding;
            int trimPadding = imageMarginBounds.Width;

            if (RightToLeft == RightToLeft.Yes)
            {
                // reverse the rectangle alignment in RightToLeft.Yes
                trimPadding += scaledTextPadding.Right;
                int width = maxItemSize.Width;
                checkRectangle.X    = width - checkRectangle.Right;
                imageRectangle.X    = width - imageRectangle.Right;
                textRectangle.X     = width - textRectangle.Right;
                arrowRectangle.X    = width - arrowRectangle.Right;
                imageMarginBounds.X = width - imageMarginBounds.Right;
            }
            else
            {
                trimPadding += scaledTextPadding.Left;
            }



            // VSWhidbey 339274 - we need to make sure that the text really appears vertically centered - this can be a problem in
            // systems which force the text rectangle to be odd.

            // force this to be an even height.
            this.maxItemSize.Height += this.maxItemSize.Height % 2;

            textRectangle.Y  = LayoutUtils.VAlign(textRectangle.Size, new Rectangle(Point.Empty, maxItemSize), ContentAlignment.MiddleCenter).Y;
            textRectangle.Y += (textRectangle.Height % 2);    // if the height is odd, push down by one px, see 339274 for picture
            state[stateMaxItemSizeValid] = true;
            this.PaddingToTrim           = trimPadding;
        }
Exemplo n.º 2
0
        private Rectangle PaintPrivate(Graphics g,
                                       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 is not null);

            if (paint && PaintBorder(paintParts))
            {
                PaintBorder(g, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
            }

            Rectangle resultBounds = Rectangle.Empty;

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

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

            Point ptCurrentCell = DataGridView.CurrentCellAddress;
            bool  cellCurrent   = ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex;
            bool  cellSelected  = (cellState & DataGridViewElementStates.Selected) != 0;
            Color brushColor    = PaintSelectionBackground(paintParts) && cellSelected
                ? cellStyle.SelectionBackColor
                : cellStyle.BackColor;

            if (paint && PaintBackground(paintParts) && !brushColor.HasTransparency())
            {
                using var brush = brushColor.GetCachedSolidBrushScope();
                g.FillRectangle(brush, valBounds);
            }

            if (cellStyle.Padding != Padding.Empty)
            {
                if (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;
            }

            Rectangle errorBounds = valBounds;

            if (formattedValue is string formattedValueStr && (paint || computeContentBounds))
            {
                // Font independent margins
                valBounds.Offset(HorizontalTextMarginLeft, VerticalTextMarginTop);
                valBounds.Width  -= HorizontalTextMarginLeft + HorizontalTextMarginRight;
                valBounds.Height -= VerticalTextMarginTop + VerticalTextMarginBottom;
                if ((cellStyle.Alignment & AnyBottom) != 0)
                {
                    valBounds.Height -= VerticalTextMarginBottom;
                }

                Font getLinkFont  = null;
                Font getHoverFont = null;
                bool isActive     = (LinkState & LinkState.Active) == LinkState.Active;

                LinkUtilities.EnsureLinkFonts(cellStyle.Font, LinkBehavior, ref getLinkFont, ref getHoverFont, isActive);
                TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(
                    DataGridView.RightToLeftInternal,
                    cellStyle.Alignment,
                    cellStyle.WrapMode);

                using Font linkFont  = getLinkFont;
                using Font hoverFont = getHoverFont;

                // Paint the focus rectangle around the link
                if (!paint)
                {
                    Debug.Assert(computeContentBounds);
                    resultBounds = DataGridViewUtilities.GetTextBounds(
                        valBounds,
                        formattedValueStr,
                        flags,
                        cellStyle,
                        LinkState == LinkState.Hover ? hoverFont : linkFont);
                }
                else
                {
                    if (valBounds.Width > 0 && valBounds.Height > 0)
                    {
                        if (cellCurrent &&
                            DataGridView.ShowFocusCues &&
                            DataGridView.Focused &&
                            PaintFocus(paintParts))
                        {
                            Rectangle focusBounds = DataGridViewUtilities.GetTextBounds(
                                valBounds,
                                formattedValueStr,
                                flags,
                                cellStyle,
                                LinkState == LinkState.Hover ? hoverFont : linkFont);

                            if ((cellStyle.Alignment & AnyLeft) != 0)
                            {
                                focusBounds.X--;
                                focusBounds.Width++;
                            }
                            else if ((cellStyle.Alignment & AnyRight) != 0)
                            {
                                focusBounds.X++;
                                focusBounds.Width++;
                            }

                            focusBounds.Height += 2;
                            ControlPaint.DrawFocusRectangle(g, focusBounds, Color.Empty, brushColor);
                        }

                        Color linkColor;
                        if ((LinkState & LinkState.Active) == LinkState.Active)
                        {
                            linkColor = ActiveLinkColor;
                        }
                        else if (LinkVisited)
                        {
                            linkColor = VisitedLinkColor;
                        }
                        else
                        {
                            linkColor = LinkColor;
                        }

                        if (PaintContentForeground(paintParts))
                        {
                            if ((flags & TextFormatFlags.SingleLine) != 0)
                            {
                                flags |= TextFormatFlags.EndEllipsis;
                            }

                            TextRenderer.DrawText(
                                g,
                                formattedValueStr,
                                LinkState == LinkState.Hover ? hoverFont : linkFont,
                                valBounds,
                                linkColor,
                                flags);
                        }
                    }
                    else if (cellCurrent &&
                             DataGridView.ShowFocusCues &&
                             DataGridView.Focused &&
                             PaintFocus(paintParts) &&
                             errorBounds.Width > 0 &&
                             errorBounds.Height > 0)
                    {
                        // Draw focus rectangle
                        ControlPaint.DrawFocusRectangle(g, errorBounds, Color.Empty, brushColor);
                    }
                }

                linkFont.Dispose();
                hoverFont.Dispose();
            }
Exemplo n.º 3
0
        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);
                }
            }
        }
Exemplo n.º 4
0
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            base.OnPaint(e);

            // Can't render without an owner
            if (this.Owner == null)
            {
                return;
            }

            // If DropDown.ShowImageMargin is false, we don't display the image
            Image draw_image = this.UseImageMargin ? this.Image : null;

            // Disable this color detection until we do the color detection for ToolStrip *completely*
            // Color font_color = this.ForeColor == SystemColors.ControlText ? SystemColors.MenuText : this.ForeColor;
            Color font_color = ForeColor;

            if ((this.Selected || this.Pressed) && this.IsOnDropDown && font_color == SystemColors.MenuText)
            {
                font_color = SystemColors.HighlightText;
            }

            if (!this.Enabled && this.ForeColor == SystemColors.ControlText)
            {
                font_color = SystemColors.GrayText;
            }

            // Gray stuff out if we're disabled
            draw_image = this.Enabled ? draw_image : ToolStripRenderer.CreateDisabledImage(draw_image);

            // Draw our background
            this.Owner.Renderer.DrawMenuItemBackground(new ToolStripItemRenderEventArgs(e.Graphics, this));

            // Figure out where our text and image go
            Rectangle text_layout_rect;
            Rectangle image_layout_rect;

            this.CalculateTextAndImageRectangles(out text_layout_rect, out image_layout_rect);

            if (this.IsOnDropDown)
            {
                if (!this.UseImageMargin)
                {
                    image_layout_rect = Rectangle.Empty;
                    text_layout_rect  = new Rectangle(8, text_layout_rect.Top, text_layout_rect.Width, text_layout_rect.Height);
                }
                else
                {
                    text_layout_rect = new Rectangle(35, text_layout_rect.Top, text_layout_rect.Width, text_layout_rect.Height);

                    if (image_layout_rect != Rectangle.Empty)
                    {
                        image_layout_rect = new Rectangle(new Point(4, 3), base.GetImageSize());
                    }
                }

                if (this.Checked && this.ShowMargin)
                {
                    this.Owner.Renderer.DrawItemCheck(new ToolStripItemImageRenderEventArgs(e.Graphics, this, new Rectangle(2, 1, 19, 19)));
                }
            }
            if (text_layout_rect != Rectangle.Empty)
            {
                this.Owner.Renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(e.Graphics, this, this.Text, text_layout_rect, font_color, this.Font, this.TextAlign));
            }

            string key_string = GetShortcutDisplayString();

            if (!string.IsNullOrEmpty(key_string) && !this.HasDropDownItems)
            {
                int       offset          = 15;
                Size      key_string_size = TextRenderer.MeasureText(key_string, this.Font);
                Rectangle key_string_rect = new Rectangle(this.ContentRectangle.Right - key_string_size.Width - offset, text_layout_rect.Top, key_string_size.Width, text_layout_rect.Height);
                this.Owner.Renderer.DrawItemText(new ToolStripItemTextRenderEventArgs(e.Graphics, this, key_string, key_string_rect, font_color, this.Font, this.TextAlign));
            }

            if (image_layout_rect != Rectangle.Empty)
            {
                this.Owner.Renderer.DrawItemImage(new ToolStripItemImageRenderEventArgs(e.Graphics, this, draw_image, image_layout_rect));
            }

            if (this.IsOnDropDown && this.HasDropDownItems && this.Parent is ToolStripDropDownMenu)
            {
                this.Owner.Renderer.DrawArrow(new ToolStripArrowRenderEventArgs(e.Graphics, this, new Rectangle(this.Bounds.Width - 17, 2, 10, 20), Color.Black, ArrowDirection.Right));
            }

            return;
        }
Exemplo n.º 5
0
        protected override void Paint(Graphics graphics,
                                      Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
                                      DataGridViewElementStates elementState, object value,
                                      object formattedValue, string errorText,
                                      DataGridViewCellStyle cellStyle,
                                      DataGridViewAdvancedBorderStyle advancedBorderStyle,
                                      DataGridViewPaintParts paintParts)
        {
            // The button cell is disabled, so paint the border,
            // background, and disabled button for the cell.
            if (!this.enabledValue)
            {
                // Draw the cell background, if specified.
                if ((paintParts & DataGridViewPaintParts.Background) ==
                    DataGridViewPaintParts.Background)
                {
                    SolidBrush cellBackground =
                        new SolidBrush(cellStyle.BackColor);
                    graphics.FillRectangle(cellBackground, cellBounds);
                    cellBackground.Dispose();
                }

                // Draw the cell borders, if specified.
                if ((paintParts & DataGridViewPaintParts.Border) ==
                    DataGridViewPaintParts.Border)
                {
                    PaintBorder(graphics, clipBounds, cellBounds, cellStyle,
                                advancedBorderStyle);
                }

                // Calculate the area in which to draw the button.
                Rectangle buttonArea       = cellBounds;
                Rectangle buttonAdjustment =
                    this.BorderWidths(advancedBorderStyle);
                buttonArea.X      += buttonAdjustment.X;
                buttonArea.Y      += buttonAdjustment.Y;
                buttonArea.Height -= buttonAdjustment.Height;
                buttonArea.Width  -= buttonAdjustment.Width;

                // Draw the disabled button.
                ButtonRenderer.DrawButton(graphics, buttonArea,
                                          PushButtonState.Disabled);

                // Draw the disabled button text.
                if (this.FormattedValue is String)
                {
                    TextRenderer.DrawText(graphics,
                                          (string)this.FormattedValue,
                                          this.DataGridView.Font,
                                          buttonArea, Color.Gray);
                }
            }
            else
            {
                // The button cell is enabled, so let the base class
                // handle the painting.
                base.Paint(graphics, clipBounds, cellBounds, rowIndex,
                           elementState, value, formattedValue, errorText,
                           cellStyle, advancedBorderStyle, paintParts);
            }
        }
Exemplo n.º 6
0
        private Rectangle PaintPrivate(Graphics g, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts, bool computeContentBounds, bool computeErrorIconBounds, bool paint)
        {
            if (paint && DataGridViewCell.PaintBorder(paintParts))
            {
                this.PaintBorder(g, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
            }
            Rectangle empty      = Rectangle.Empty;
            Rectangle rectangle2 = this.BorderWidths(advancedBorderStyle);
            Rectangle rect       = cellBounds;

            rect.Offset(rectangle2.X, rectangle2.Y);
            rect.Width  -= rectangle2.Right;
            rect.Height -= rectangle2.Bottom;
            Point      currentCellAddress = base.DataGridView.CurrentCellAddress;
            bool       flag        = (currentCellAddress.X == base.ColumnIndex) && (currentCellAddress.Y == rowIndex);
            bool       flag2       = (cellState & DataGridViewElementStates.Selected) != DataGridViewElementStates.None;
            SolidBrush cachedBrush = base.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && flag2) ? cellStyle.SelectionBackColor : cellStyle.BackColor);

            if ((paint && DataGridViewCell.PaintBackground(paintParts)) && (cachedBrush.Color.A == 0xff))
            {
                g.FillRectangle(cachedBrush, rect);
            }
            if (cellStyle.Padding != Padding.Empty)
            {
                if (base.DataGridView.RightToLeftInternal)
                {
                    rect.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
                }
                else
                {
                    rect.Offset(cellStyle.Padding.Left, cellStyle.Padding.Top);
                }
                rect.Width  -= cellStyle.Padding.Horizontal;
                rect.Height -= cellStyle.Padding.Vertical;
            }
            Rectangle rectangle = rect;
            string    text      = formattedValue as string;

            if ((text != null) && (paint || computeContentBounds))
            {
                rect.Offset(1, 1);
                rect.Width  -= 3;
                rect.Height -= 2;
                if ((cellStyle.Alignment & anyBottom) != DataGridViewContentAlignment.NotSet)
                {
                    rect.Height--;
                }
                Font linkFont      = null;
                Font hoverLinkFont = null;
                LinkUtilities.EnsureLinkFonts(cellStyle.Font, this.LinkBehavior, ref linkFont, ref hoverLinkFont);
                TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(base.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
                if (paint)
                {
                    if ((rect.Width > 0) && (rect.Height > 0))
                    {
                        Color activeLinkColor;
                        if ((flag && base.DataGridView.ShowFocusCues) && (base.DataGridView.Focused && DataGridViewCell.PaintFocus(paintParts)))
                        {
                            Rectangle rectangle5 = DataGridViewUtilities.GetTextBounds(rect, text, flags, cellStyle, (this.LinkState == System.Windows.Forms.LinkState.Hover) ? hoverLinkFont : linkFont);
                            if ((cellStyle.Alignment & anyLeft) != DataGridViewContentAlignment.NotSet)
                            {
                                rectangle5.X--;
                                rectangle5.Width++;
                            }
                            else if ((cellStyle.Alignment & anyRight) != DataGridViewContentAlignment.NotSet)
                            {
                                rectangle5.X++;
                                rectangle5.Width++;
                            }
                            rectangle5.Height += 2;
                            ControlPaint.DrawFocusRectangle(g, rectangle5, Color.Empty, cachedBrush.Color);
                        }
                        if ((this.LinkState & System.Windows.Forms.LinkState.Active) == System.Windows.Forms.LinkState.Active)
                        {
                            activeLinkColor = this.ActiveLinkColor;
                        }
                        else if (this.LinkVisited)
                        {
                            activeLinkColor = this.VisitedLinkColor;
                        }
                        else
                        {
                            activeLinkColor = this.LinkColor;
                        }
                        if (DataGridViewCell.PaintContentForeground(paintParts))
                        {
                            if ((flags & TextFormatFlags.SingleLine) != TextFormatFlags.Default)
                            {
                                flags |= TextFormatFlags.EndEllipsis;
                            }
                            TextRenderer.DrawText(g, text, (this.LinkState == System.Windows.Forms.LinkState.Hover) ? hoverLinkFont : linkFont, rect, activeLinkColor, flags);
                        }
                    }
                    else if (((flag && base.DataGridView.ShowFocusCues) && (base.DataGridView.Focused && DataGridViewCell.PaintFocus(paintParts))) && ((rectangle.Width > 0) && (rectangle.Height > 0)))
                    {
                        ControlPaint.DrawFocusRectangle(g, rectangle, Color.Empty, cachedBrush.Color);
                    }
                }
                else
                {
                    empty = DataGridViewUtilities.GetTextBounds(rect, text, flags, cellStyle, (this.LinkState == System.Windows.Forms.LinkState.Hover) ? hoverLinkFont : linkFont);
                }
                linkFont.Dispose();
                hoverLinkFont.Dispose();
            }
            else if (paint || computeContentBounds)
            {
                if (((flag && base.DataGridView.ShowFocusCues) && (base.DataGridView.Focused && DataGridViewCell.PaintFocus(paintParts))) && ((paint && (rect.Width > 0)) && (rect.Height > 0)))
                {
                    ControlPaint.DrawFocusRectangle(g, rect, Color.Empty, cachedBrush.Color);
                }
            }
            else if (computeErrorIconBounds && !string.IsNullOrEmpty(errorText))
            {
                empty = base.ComputeErrorIconBounds(rectangle);
            }
            if ((base.DataGridView.ShowCellErrors && paint) && DataGridViewCell.PaintErrorIcon(paintParts))
            {
                base.PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, rectangle, errorText);
            }
            return(empty);
        }
Exemplo n.º 7
0
        /// <summary>
        ///    Initializes a new instance of the <see cref='System.Windows.Forms.ThreadExceptionDialog'/> class.
        /// </summary>
        public ThreadExceptionDialog(Exception t)
        {
            if (DpiHelper.IsScalingRequirementMet)
            {
                scaledMaxWidth                        = LogicalToDeviceUnits(MAXWIDTH);
                scaledMaxHeight                       = LogicalToDeviceUnits(MAXHEIGHT);
                scaledPaddingWidth                    = LogicalToDeviceUnits(PADDINGWIDTH);
                scaledPaddingHeight                   = LogicalToDeviceUnits(PADDINGHEIGHT);
                scaledMaxTextWidth                    = LogicalToDeviceUnits(MAXTEXTWIDTH);
                scaledMaxTextHeight                   = LogicalToDeviceUnits(MAXTEXTHEIGHT);
                scaledButtonTopPadding                = LogicalToDeviceUnits(BUTTONTOPPADDING);
                scaledButtonDetailsLeftPadding        = LogicalToDeviceUnits(BUTTONDETAILS_LEFTPADDING);
                scaledMessageTopPadding               = LogicalToDeviceUnits(MESSAGE_TOPPADDING);
                scaledHeightPadding                   = LogicalToDeviceUnits(HEIGHTPADDING);
                scaledButtonWidth                     = LogicalToDeviceUnits(BUTTONWIDTH);
                scaledButtonHeight                    = LogicalToDeviceUnits(BUTTONHEIGHT);
                scaledButtonAlignmentWidth            = LogicalToDeviceUnits(BUTTONALIGNMENTWIDTH);
                scaledButtonAlignmentPadding          = LogicalToDeviceUnits(BUTTONALIGNMENTPADDING);
                scaledDetailsWidthPadding             = LogicalToDeviceUnits(DETAILSWIDTHPADDING);
                scaledDetailsHeight                   = LogicalToDeviceUnits(DETAILSHEIGHT);
                scaledPictureWidth                    = LogicalToDeviceUnits(PICTUREWIDTH);
                scaledPictureHeight                   = LogicalToDeviceUnits(PICTUREHEIGHT);
                scaledExceptionMessageVerticalPadding = LogicalToDeviceUnits(EXCEPTIONMESSAGEVERTICALPADDING);
            }

            string messageFormat;
            string messageText;

            Button[] buttons;
            bool     detailAnchor = false;

            if (t is WarningException w)
            {
                messageFormat = SR.ExDlgWarningText;
                messageText   = w.Message;
                if (w.HelpUrl == null)
                {
                    buttons = new Button[] { continueButton };
                }
                else
                {
                    buttons = new Button[] { continueButton, helpButton };
                }
            }
            else
            {
                messageText = t.Message;

                detailAnchor = true;

                if (Application.AllowQuit)
                {
                    if (t is System.Security.SecurityException)
                    {
                        messageFormat = SR.ExDlgSecurityErrorText;
                    }
                    else
                    {
                        messageFormat = SR.ExDlgErrorText;
                    }
                    buttons = new Button[] { detailsButton, continueButton, quitButton };
                }
                else
                {
                    if (t is System.Security.SecurityException)
                    {
                        messageFormat = SR.ExDlgSecurityContinueErrorText;
                    }
                    else
                    {
                        messageFormat = SR.ExDlgContinueErrorText;
                    }
                    buttons = new Button[] { detailsButton, continueButton };
                }
            }

            if (messageText.Length == 0)
            {
                messageText = t.GetType().Name;
            }
            if (t is System.Security.SecurityException)
            {
                messageText = string.Format(messageFormat, t.GetType().Name, Trim(messageText));
            }
            else
            {
                messageText = string.Format(messageFormat, Trim(messageText));
            }

            StringBuilder detailsTextBuilder = new StringBuilder();
            string        newline            = "\r\n";
            string        separator          = SR.ExDlgMsgSeperator;
            string        sectionseparator   = SR.ExDlgMsgSectionSeperator;

            if (Application.CustomThreadExceptionHandlerAttached)
            {
                detailsTextBuilder.Append(SR.ExDlgMsgHeaderNonSwitchable);
            }
            else
            {
                detailsTextBuilder.Append(SR.ExDlgMsgHeaderSwitchable);
            }
            detailsTextBuilder.Append(string.Format(CultureInfo.CurrentCulture, sectionseparator, SR.ExDlgMsgExceptionSection));
            detailsTextBuilder.Append(t.ToString());
            detailsTextBuilder.Append(newline);
            detailsTextBuilder.Append(newline);
            detailsTextBuilder.Append(string.Format(CultureInfo.CurrentCulture, sectionseparator, SR.ExDlgMsgLoadedAssembliesSection));

            foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                AssemblyName name    = asm.GetName();
                string       fileVer = SR.NotAvailable;

                try
                {
                    if (name.EscapedCodeBase != null && name.EscapedCodeBase.Length > 0)
                    {
                        Uri codeBase = new Uri(name.EscapedCodeBase);
                        if (codeBase.Scheme == "file")
                        {
                            fileVer = FileVersionInfo.GetVersionInfo(NativeMethods.GetLocalPath(name.EscapedCodeBase)).FileVersion;
                        }
                    }
                }
                catch (System.IO.FileNotFoundException)
                {
                }
                detailsTextBuilder.Append(string.Format(SR.ExDlgMsgLoadedAssembliesEntry, name.Name, name.Version, fileVer, name.EscapedCodeBase));
                detailsTextBuilder.Append(separator);
            }

            detailsTextBuilder.Append(string.Format(CultureInfo.CurrentCulture, sectionseparator, SR.ExDlgMsgJITDebuggingSection));
            if (Application.CustomThreadExceptionHandlerAttached)
            {
                detailsTextBuilder.Append(SR.ExDlgMsgFooterNonSwitchable);
            }
            else
            {
                detailsTextBuilder.Append(SR.ExDlgMsgFooterSwitchable);
            }

            detailsTextBuilder.Append(newline);
            detailsTextBuilder.Append(newline);

            string detailsText = detailsTextBuilder.ToString();

            Graphics g = message.CreateGraphicsInternal();

            Size textSize = new Size(scaledMaxWidth - scaledPaddingWidth, int.MaxValue);

            if (DpiHelper.IsScalingRequirementMet && Label.UseCompatibleTextRenderingDefault == false)
            {
                // we need to measure string using API that matches the rendering engine - TextRenderer.MeasureText for GDI
                textSize = Size.Ceiling(TextRenderer.MeasureText(messageText, Font, textSize, TextFormatFlags.WordBreak));
            }
            else
            {
                // if HighDpi improvements are not enabled, or rendering mode is GDI+, use Graphics.MeasureString
                textSize = Size.Ceiling(g.MeasureString(messageText, Font, textSize.Width));
            }

            textSize.Height += scaledExceptionMessageVerticalPadding;
            g.Dispose();

            if (textSize.Width < scaledMaxTextWidth)
            {
                textSize.Width = scaledMaxTextWidth;
            }

            if (textSize.Height > scaledMaxHeight)
            {
                textSize.Height = scaledMaxHeight;
            }

            int width     = textSize.Width + scaledPaddingWidth;
            int buttonTop = Math.Max(textSize.Height, scaledMaxTextHeight) + scaledPaddingHeight;

            Form activeForm = Form.ActiveForm;

            if (activeForm == null || activeForm.Text.Length == 0)
            {
                Text = SR.ExDlgCaption;
            }
            else
            {
                Text = string.Format(SR.ExDlgCaption2, activeForm.Text);
            }

            AcceptButton    = continueButton;
            CancelButton    = continueButton;
            FormBorderStyle = FormBorderStyle.FixedDialog;
            MaximizeBox     = false;
            MinimizeBox     = false;
            StartPosition   = FormStartPosition.CenterScreen;
            Icon            = null;
            ClientSize      = new Size(width, buttonTop + scaledButtonTopPadding);
            TopMost         = true;

            pictureBox.Location = new Point(scaledPictureWidth / 8, scaledPictureHeight / 8);
            pictureBox.Size     = new Size(scaledPictureWidth * 3 / 4, scaledPictureHeight * 3 / 4);
            pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
            if (t is System.Security.SecurityException)
            {
                pictureBox.Image = SystemIcons.Information.ToBitmap();
            }
            else
            {
                pictureBox.Image = SystemIcons.Error.ToBitmap();
            }
            Controls.Add(pictureBox);
            message.SetBounds(scaledPictureWidth,
                              scaledMessageTopPadding + (scaledMaxTextHeight - Math.Min(textSize.Height, scaledMaxTextHeight)) / 2,
                              textSize.Width, textSize.Height);
            message.Text = messageText;
            Controls.Add(message);

            continueButton.Text         = SR.ExDlgContinue;
            continueButton.FlatStyle    = FlatStyle.Standard;
            continueButton.DialogResult = DialogResult.Cancel;

            quitButton.Text         = SR.ExDlgQuit;
            quitButton.FlatStyle    = FlatStyle.Standard;
            quitButton.DialogResult = DialogResult.Abort;

            helpButton.Text         = SR.ExDlgHelp;
            helpButton.FlatStyle    = FlatStyle.Standard;
            helpButton.DialogResult = DialogResult.Yes;

            detailsButton.Text      = SR.ExDlgShowDetails;
            detailsButton.FlatStyle = FlatStyle.Standard;
            detailsButton.Click    += new EventHandler(DetailsClick);

            Button b          = null;
            int    startIndex = 0;

            if (detailAnchor)
            {
                b = detailsButton;

                expandImage   = DpiHelper.GetBitmapFromIcon(GetType(), DownBitmapName);
                collapseImage = DpiHelper.GetBitmapFromIcon(GetType(), UpBitmapName);

                if (DpiHelper.IsScalingRequirementMet)
                {
                    ScaleBitmapLogicalToDevice(ref expandImage);
                    ScaleBitmapLogicalToDevice(ref collapseImage);
                }

                b.SetBounds(scaledButtonDetailsLeftPadding, buttonTop, scaledButtonWidth, scaledButtonHeight);
                b.Image      = expandImage;
                b.ImageAlign = ContentAlignment.MiddleLeft;
                Controls.Add(b);
                startIndex = 1;
            }

            int buttonLeft = (width - scaledButtonDetailsLeftPadding - ((buttons.Length - startIndex) * scaledButtonAlignmentWidth - scaledButtonAlignmentPadding));

            for (int i = startIndex; i < buttons.Length; i++)
            {
                b = buttons[i];
                b.SetBounds(buttonLeft, buttonTop, scaledButtonWidth, scaledButtonHeight);
                Controls.Add(b);
                buttonLeft += scaledButtonAlignmentWidth;
            }

            details.Text          = detailsText;
            details.ScrollBars    = ScrollBars.Both;
            details.Multiline     = true;
            details.ReadOnly      = true;
            details.WordWrap      = false;
            details.TabStop       = false;
            details.AcceptsReturn = false;

            details.SetBounds(scaledButtonDetailsLeftPadding, buttonTop + scaledButtonTopPadding, width - scaledDetailsWidthPadding, scaledDetailsHeight);
            details.Visible = detailsVisible;
            Controls.Add(details);
            if (DpiHelper.IsScalingRequirementMet)
            {
                DpiChanged += ThreadExceptionDialog_DpiChanged;
            }
        }
Exemplo n.º 8
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);
                }
            }
        }
        /// <summary>
        /// Paints the control.
        /// </summary>
        /// <param name="e">The <see cref="PaintEventArgs"/> instance containing the event data.</param>
        protected virtual void PaintControl(PaintEventArgs e)
        {
            var cbi = NativeMethods.COMBOBOXINFO.FromComboBox(this);

            var       itemText = SelectedIndex >= 0 ? GetItemText(SelectedItem) : string.Empty;
            var       state    = Enabled ? currentState : ComboBoxState.Disabled;
            Rectangle tr       = cbi.rcItem;

            /*Rectangle tr = this.ClientRectangle;
             * tr.Width -= (SystemInformation.VerticalScrollBarWidth + 2);
             * tr.Inflate(0, -2);
             * tr.Offset(1, 0);*/
            Rectangle br        = cbi.rcButton;
            var       vsSuccess = false;

            if (VisualStyleRenderer.IsSupported && Application.RenderWithVisualStyles)
            {
                /*Rectangle r = Rectangle.Inflate(this.ClientRectangle, 1, 1);
                 * if (this.DropDownStyle != ComboBoxStyle.DropDownList)
                 * {
                 *      e.Graphics.Clear(this.BackColor);
                 *      ComboBoxRenderer.DrawTextBox(e.Graphics, r, itemText, this.Font, tr, tff, state);
                 *      ComboBoxRenderer.DrawDropDownButton(e.Graphics, br, state);
                 * }
                 * else*/
                {
                    try
                    {
                        var vr = new VisualStyleRenderer("Combobox", DropDownStyle == ComboBoxStyle.DropDownList ? 5 : 4, (int)state);
                        vr.DrawParentBackground(e.Graphics, ClientRectangle, this);
                        vr.DrawBackground(e.Graphics, ClientRectangle);
                        if (DropDownStyle != ComboBoxStyle.DropDownList)
                        {
                            br.Inflate(1, 1);
                        }
                        var cr = DropDownStyle == ComboBoxStyle.DropDownList ? Rectangle.Inflate(br, -1, -1) : br;
                        vr.SetParameters("Combobox", 7, (int)(br.Contains(PointToClient(Cursor.Position)) ? state : ComboBoxState.Normal));
                        vr.DrawBackground(e.Graphics, br, cr);
                        if (Focused && State != ComboBoxState.Pressed)
                        {
                            var sz = TextRenderer.MeasureText(e.Graphics, "Wg", Font, tr.Size, TextFormatFlags.Default);
                            var fr = Rectangle.Inflate(tr, 0, (sz.Height - tr.Height) / 2 + 1);
                            ControlPaint.DrawFocusRectangle(e.Graphics, fr);
                        }
                        var fgc = Enabled ? ForeColor : SystemColors.GrayText;
                        TextRenderer.DrawText(e.Graphics, itemText, Font, tr, fgc, tff);
                        vsSuccess = true;
                    }
                    catch { }
                }
            }

            if (!vsSuccess)
            {
                Diagnostics.Debug.WriteLine($"CR:{ClientRectangle};ClR:{e.ClipRectangle};Foc:{Focused};St:{state};Tx:{itemText}");
                var focusedNotPressed = Focused && state != ComboBoxState.Pressed;
                var bgc = Enabled ? (focusedNotPressed ? SystemColors.Highlight : BackColor) : SystemColors.Control;
                var fgc = Enabled ? (focusedNotPressed ? SystemColors.HighlightText : ForeColor) : SystemColors.GrayText;
                e.Graphics.Clear(bgc);
                ControlPaint.DrawBorder3D(e.Graphics, ClientRectangle, Border3DStyle.Sunken);
                ControlPaint.DrawComboButton(e.Graphics, br, Enabled ? (state == ComboBoxState.Pressed ? ButtonState.Pushed : ButtonState.Normal) : ButtonState.Inactive);
                tr = new Rectangle(tr.X + 3, tr.Y + 1, tr.Width - 4, tr.Height - 2);
                TextRenderer.DrawText(e.Graphics, itemText, Font, tr, fgc, tff);
                if (focusedNotPressed)
                {
                    var fr = Rectangle.Inflate(cbi.rcItem, -1, -1);
                    fr.Height++;
                    fr.Width++;
                    ControlPaint.DrawFocusRectangle(e.Graphics, fr, fgc, bgc);
                    e.Graphics.DrawRectangle(SystemPens.Window, cbi.rcItem);
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        ///     关闭Tab之前触发事件
        /// </summary>
        /// <summary>
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (!Visible)
            {
                return;
            }
            //画选点击选项卡,
            if (TabCount > 0)
            {
                var g = e.Graphics;
                Share.GraphicSetup(g);
                //  g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                // g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
                // g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                // alpha = Alpha.Normal;
                var sb = new SolidBrush(Share.BackColor);

                var pen = new Pen(Share.BorderColor);
                //   g.FillPath(sb, GetPath(ClientRectangle, 5)); //画整体边框
                //   g.DrawPath(pen, GetPath(ClientRectangle, 5)); //画整体背景
                var tabRect       = Rectangle.Empty;
                var selecttabRect = Rectangle.Empty;
                // Point cursorPoint = this.PointToClient(MousePosition);
                TabPage      page       = null;
                TabPage      selectPage = null;
                GraphicsPath gp         = null;
                GraphicsPath selectgp   = null;

                for (var i = 0; i < TabCount; i++)
                {
                    page       = TabPages[i];
                    tabRect    = GetTabRect(i);
                    tabRect.X += 2;
                    tabRect.Y += 2;
                    gp         = DrawHelper.GetGoogleTabPath(tabRect, 8);
                    if (SelectedIndex != i)
                    {
                        //  alpha = Alpha.MoveOrUp;
                        page.ForeColor = Color.CornflowerBlue;
                        //   sb = new SolidBrush(color);
                        //   pen = new Pen(color);
                        sb.Color = Share.DisabelBackColor;

                        g.FillPath(sb, gp);  //画边框
                        g.DrawPath(pen, gp); //画背景
                        gp.Dispose();
                        //  sb.Dispose();
                        //渲染选项卡文字
                        tabRect.X     += 10; //让文字往右偏移10个像素.因为谷歌的tab 是个梯形的
                        tabRect.Width -= 20;
                        TextRenderer.DrawText(g, page.Text, page.Font, tabRect,
                                              page.ForeColor,
                                              TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis |
                                              TextFormatFlags.HorizontalCenter);
                    }
                    else
                    {
                        selectPage    = page;
                        selectgp      = gp;
                        selecttabRect = tabRect;
                    }
                    if (i == TabCount - 1)
                    {
                        selectPage.ForeColor = Color.Orange;
                        // alpha = Alpha.a200;
                        //  sb = new SolidBrush(color);
                        //  pen = new Pen(color);
                        sb.Color = Share.BackColor;
                        g.FillPath(sb, selectgp);  //画背景
                        g.DrawPath(pen, selectgp); //画边框
                        selectgp.Dispose();
                        // sb.Dispose();
                        //画叉叉 ,叉叉是在最上层的, 所以要最后画
                        Bitmap clsBitmap;
                        if (closeState == MouseState.press)
                        {
                            clsBitmap = Properties.Resources.icon_tbclose_press;
                        }
                        else if (closeState == MouseState.move)
                        {
                            clsBitmap = Properties.Resources.icon_tbclose_hover;
                        }
                        else
                        {
                            clsBitmap = Properties.Resources.icon_tbclose_normal;
                        }
                        g.DrawImage(clsBitmap, GetCloseRect(selecttabRect));
                        clsBitmap.Dispose();
                        //渲染选项卡文字
                        selecttabRect.X     += 10; //让文字往右偏移10个像素.因为谷歌的tab 是个梯形的
                        selecttabRect.Width -= 20;
                        TextRenderer.DrawText(g, selectPage.Text, selectPage.Font, selecttabRect,
                                              selectPage.ForeColor,
                                              TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis |
                                              TextFormatFlags.HorizontalCenter);

                        var rect = new Rectangle(GetTabRect(0).X + 2,
                                                 GetTabRect(0).Bottom + 2,
                                                 TabPages[0].DisplayRectangle.Width + 6,
                                                 TabPages[0].DisplayRectangle.Height + 6);
                        var path = GetPath(rect, 5);
                        pen.Color = Share.BorderColor;
                        g.DrawPath(pen, path); //画页面边框
                        path.Dispose();
                    }
                }
                sb.Dispose();
                pen.Dispose();
            }
        }
Exemplo n.º 11
0
        private Rectangle PaintPrivate(Graphics g,
                                       Rectangle clipBounds,
                                       Rectangle cellBounds,
                                       int rowIndex,
                                       DataGridViewElementStates elementState,
                                       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);

            Point ptCurrentCell = DataGridView.CurrentCellAddress;
            bool  cellSelected  = (elementState & DataGridViewElementStates.Selected) != 0;
            bool  cellCurrent   = (ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex);

            Rectangle resultBounds;
            string    formattedString = formattedValue as string;

            Color backBrushColor = PaintSelectionBackground(paintParts) && cellSelected
                ? cellStyle.SelectionBackColor
                : cellStyle.BackColor;
            Color foreBrushColor = cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor;

            if (paint && PaintBorder(paintParts))
            {
                PaintBorder(g, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
            }

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

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

            if (valBounds.Height <= 0 || valBounds.Width <= 0)
            {
                return(Rectangle.Empty);
            }

            if (paint && PaintBackground(paintParts) && !backBrushColor.HasTransparency())
            {
                using var backBrush = backBrushColor.GetCachedSolidBrushScope();
                g.FillRectangle(backBrush, valBounds);
            }

            if (cellStyle.Padding != Padding.Empty)
            {
                if (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;
            }

            Rectangle errorBounds = valBounds;

            if (valBounds.Height > 0 && valBounds.Width > 0 && (paint || computeContentBounds))
            {
                switch (FlatStyle)
                {
                case FlatStyle.Standard:
                case FlatStyle.System:
                    if (DataGridView.ApplyVisualStylesToInnerCells)
                    {
                        if (paint && PaintContentBackground(paintParts))
                        {
                            PushButtonState pbState = VisualStyles.PushButtonState.Normal;
                            if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0)
                            {
                                pbState = PushButtonState.Pressed;
                            }
                            else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex &&
                                     DataGridView.MouseEnteredCellAddress.X == ColumnIndex && mouseInContentBounds)
                            {
                                pbState = PushButtonState.Hot;
                            }

                            if (PaintFocus(paintParts) && cellCurrent && DataGridView.ShowFocusCues && DataGridView.Focused)
                            {
                                pbState |= PushButtonState.Default;
                            }

                            DataGridViewButtonCellRenderer.DrawButton(g, valBounds, (int)pbState);
                        }

                        resultBounds = valBounds;
                        valBounds    = DataGridViewButtonCellRenderer.DataGridViewButtonRenderer.GetBackgroundContentRectangle(g, valBounds);
                    }
                    else
                    {
                        if (paint && PaintContentBackground(paintParts))
                        {
                            ControlPaint.DrawBorder(
                                g,
                                valBounds,
                                SystemColors.Control,
                                (ButtonState == ButtonState.Normal) ? ButtonBorderStyle.Outset : ButtonBorderStyle.Inset);
                        }
                        resultBounds = valBounds;
                        valBounds.Inflate(-SystemInformation.Border3DSize.Width, -SystemInformation.Border3DSize.Height);
                    }

                    break;

                case FlatStyle.Flat:
                    // ButtonBase::PaintFlatDown and ButtonBase::PaintFlatUp paint the border in the same way
                    valBounds.Inflate(-1, -1);
                    if (paint && PaintContentBackground(paintParts))
                    {
                        ButtonBaseAdapter.DrawDefaultBorder(g, valBounds, backBrushColor, isDefault: true);

                        if (!backBrushColor.HasTransparency())
                        {
                            if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0)
                            {
                                ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintFlatRender(
                                    g,
                                    cellStyle.ForeColor,
                                    cellStyle.BackColor,
                                    DataGridView.Enabled).Calculate();

                                using var hdc    = new DeviceContextHdcScope(g);
                                using var hbrush = new Gdi32.CreateBrushScope(
                                          colors.Options.HighContrast ? colors.ButtonShadow : colors.LowHighlight);
                                hdc.FillRectangle(valBounds, hbrush);
                            }
                            else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex &&
                                     DataGridView.MouseEnteredCellAddress.X == ColumnIndex && mouseInContentBounds)
                            {
                                using var hdc    = new DeviceContextHdcScope(g);
                                using var hbrush = new Gdi32.CreateBrushScope(SystemColors.ControlDark);
                                hdc.FillRectangle(valBounds, hbrush);
                            }
                        }
                    }

                    resultBounds = valBounds;
                    break;

                default:
                    Debug.Assert(FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style");
                    valBounds.Inflate(-1, -1);
                    if (paint && PaintContentBackground(paintParts))
                    {
                        if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0)
                        {
                            // paint down
                            ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(
                                g,
                                cellStyle.ForeColor,
                                cellStyle.BackColor,
                                DataGridView.Enabled).Calculate();
                            ButtonBaseAdapter.DrawDefaultBorder(
                                g,
                                valBounds,
                                colors.Options.HighContrast ? colors.WindowText : colors.WindowFrame,
                                isDefault: true);
                            ControlPaint.DrawBorder(
                                g,
                                valBounds,
                                colors.Options.HighContrast ? colors.WindowText : colors.ButtonShadow,
                                ButtonBorderStyle.Solid);
                        }
                        else if (DataGridView.MouseEnteredCellAddress.Y == rowIndex &&
                                 DataGridView.MouseEnteredCellAddress.X == ColumnIndex &&
                                 mouseInContentBounds)
                        {
                            // paint over
                            ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(
                                g,
                                cellStyle.ForeColor,
                                cellStyle.BackColor,
                                DataGridView.Enabled).Calculate();
                            ButtonBaseAdapter.DrawDefaultBorder(
                                g,
                                valBounds,
                                colors.Options.HighContrast ? colors.WindowText : colors.ButtonShadow,
                                isDefault: false);
                            ButtonBaseAdapter.Draw3DLiteBorder(g, valBounds, colors, true);
                        }
                        else
                        {
                            // paint up
                            ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(
                                g,
                                cellStyle.ForeColor,
                                cellStyle.BackColor,
                                DataGridView.Enabled).Calculate();
                            ButtonBaseAdapter.DrawDefaultBorder(
                                g,
                                valBounds,
                                colors.Options.HighContrast ? colors.WindowText : colors.ButtonShadow,
                                isDefault: false);
                            ControlPaint.DrawBorderSimple(
                                g,
                                valBounds,
                                colors.Options.HighContrast ? colors.WindowText : colors.ButtonShadow);
                        }
                    }

                    resultBounds = valBounds;
                    break;
                }
            }
            else if (computeErrorIconBounds)
            {
                if (!string.IsNullOrEmpty(errorText))
                {
                    resultBounds = ComputeErrorIconBounds(errorBounds);
                }
                else
                {
                    resultBounds = Rectangle.Empty;
                }
            }
            else
            {
                Debug.Assert(valBounds.Height <= 0 || valBounds.Width <= 0);
                resultBounds = Rectangle.Empty;
            }

            if (paint &&
                PaintFocus(paintParts) &&
                cellCurrent &&
                DataGridView.ShowFocusCues &&
                DataGridView.Focused &&
                valBounds.Width > 2 * SystemInformation.Border3DSize.Width + 1 &&
                valBounds.Height > 2 * SystemInformation.Border3DSize.Height + 1)
            {
                // Draw focus rectangle
                if (FlatStyle == FlatStyle.System || FlatStyle == FlatStyle.Standard)
                {
                    ControlPaint.DrawFocusRectangle(g, Rectangle.Inflate(valBounds, -1, -1), Color.Empty, SystemColors.Control);
                }
                else if (FlatStyle == FlatStyle.Flat)
                {
                    if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 ||
                        (DataGridView.CurrentCellAddress.Y == rowIndex && DataGridView.CurrentCellAddress.X == ColumnIndex))
                    {
                        ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintFlatRender(
                            g,
                            cellStyle.ForeColor,
                            cellStyle.BackColor,
                            DataGridView.Enabled).Calculate();

                        string text = formattedString ?? string.Empty;

                        ButtonBaseAdapter.LayoutOptions options = ButtonFlatAdapter.PaintFlatLayout(
                            true,
                            SystemInformation.HighContrast,
                            1,
                            valBounds,
                            Padding.Empty,
                            false,
                            cellStyle.Font,
                            text,
                            DataGridView.Enabled,
                            DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment),
                            DataGridView.RightToLeft);
                        options.DotNetOneButtonCompat = false;
                        ButtonBaseAdapter.LayoutData layout = options.Layout();

                        ButtonBaseAdapter.DrawFlatFocus(
                            g,
                            layout.Focus,
                            colors.Options.HighContrast ? colors.WindowText : colors.ConstrastButtonShadow);
                    }
                }
                else
                {
                    Debug.Assert(FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style");
                    if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 ||
                        (DataGridView.CurrentCellAddress.Y == rowIndex && DataGridView.CurrentCellAddress.X == ColumnIndex))
                    {
                        // If we are painting the current cell, then paint the text up.
                        // If we are painting the current cell and the current cell is pressed down, then paint the text down.
                        bool   paintUp = (ButtonState == ButtonState.Normal);
                        string text    = formattedString ?? string.Empty;
                        ButtonBaseAdapter.LayoutOptions options = ButtonPopupAdapter.PaintPopupLayout(
                            paintUp,
                            SystemInformation.HighContrast ? 2 : 1,
                            valBounds,
                            Padding.Empty,
                            false,
                            cellStyle.Font,
                            text,
                            DataGridView.Enabled,
                            DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment),
                            DataGridView.RightToLeft);
                        options.DotNetOneButtonCompat = false;
                        ButtonBaseAdapter.LayoutData layout = options.Layout();

                        ControlPaint.DrawFocusRectangle(
                            g,
                            layout.Focus,
                            cellStyle.ForeColor,
                            cellStyle.BackColor);
                    }
                }
            }

            if (formattedString != null && paint && PaintContentForeground(paintParts))
            {
                // Font independent margins
                valBounds.Offset(DATAGRIDVIEWBUTTONCELL_horizontalTextMargin, DATAGRIDVIEWBUTTONCELL_verticalTextMargin);
                valBounds.Width  -= 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin;
                valBounds.Height -= 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin;

                if ((ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 &&
                    FlatStyle != FlatStyle.Flat && FlatStyle != FlatStyle.Popup)
                {
                    valBounds.Offset(1, 1);
                    valBounds.Width--;
                    valBounds.Height--;
                }

                if (valBounds.Width > 0 && valBounds.Height > 0)
                {
                    Color textColor;
                    if (DataGridView.ApplyVisualStylesToInnerCells &&
                        (FlatStyle == FlatStyle.System || FlatStyle == FlatStyle.Standard))
                    {
                        textColor = DataGridViewButtonCellRenderer.DataGridViewButtonRenderer.GetColor(ColorProperty.TextColor);
                    }
                    else
                    {
                        textColor = foreBrushColor;
                    }

                    TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(
                        DataGridView.RightToLeftInternal,
                        cellStyle.Alignment,
                        cellStyle.WrapMode);

                    TextRenderer.DrawText(
                        g,
                        formattedString,
                        cellStyle.Font,
                        valBounds,
                        textColor,
                        flags);
                }
            }

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

            return(resultBounds);
        }
Exemplo n.º 12
0
 public void DrawText(TextFormatFlags flags)
 {
     TextRenderer.DrawText(graphics, item.Text, item.Font, bounds, item.ForeColor, flags);
 }
Exemplo n.º 13
0
 public void DrawText(TextFormatFlags flags)
 {
     TextRenderer.DrawTextInternal(graphics, tooltip_text, font, bounds, fore_color, flags, false);
 }
Exemplo n.º 14
0
        private void CreateLinkPieces()
        {
            if (Text.Length == 0)
            {
                SetStyle(ControlStyles.Selectable, false);
                TabStop          = false;
                link_area.Start  = 0;
                link_area.Length = 0;
                return;
            }

            if (Links.Count == 1 && Links[0].Start == 0 && Links[0].Length == -1)
            {
                Links[0].Length = Text.Length;
            }

            SortLinks();

            // Set the LinkArea values based on first link.
            if (Links.Count > 0)
            {
                link_area.Start  = Links[0].Start;
                link_area.Length = Links[0].Length;
            }
            else
            {
                link_area.Start  = 0;
                link_area.Length = 0;
            }

            TabStop = (LinkArea.Length > 0);
            SetStyle(ControlStyles.Selectable, TabStop);

            /* don't bother doing the rest if our handle hasn't been created */
            if (!IsHandleCreated)
            {
                return;
            }

            ArrayList pieces_list = new ArrayList();

            int current_end = 0;

            for (int l = 0; l < sorted_links.Length; l++)
            {
                int new_link_start = sorted_links[l].Start;

                if (new_link_start > current_end)
                {
                    /* create/push a piece
                     * containing the text between
                     * the previous/new link */
                    ArrayList text_pieces = CreatePiecesFromText(current_end, new_link_start - current_end, null);
                    pieces_list.AddRange(text_pieces);
                }

                /* now create a group of pieces for
                 * the new link (split up by \n's) */
                ArrayList link_pieces = CreatePiecesFromText(new_link_start, sorted_links[l].Length, sorted_links[l]);
                pieces_list.AddRange(link_pieces);
                sorted_links[l].pieces.AddRange(link_pieces);

                current_end = sorted_links[l].Start + sorted_links[l].Length;
            }
            if (current_end < Text.Length)
            {
                ArrayList text_pieces = CreatePiecesFromText(current_end, Text.Length - current_end, null);
                pieces_list.AddRange(text_pieces);
            }

            pieces = new Piece[pieces_list.Count];
            pieces_list.CopyTo(pieces, 0);

            CharacterRange[] ranges = new CharacterRange[pieces.Length];

            for (int i = 0; i < pieces.Length; i++)
            {
                ranges[i] = new CharacterRange(pieces[i].start, pieces[i].length);
            }

            string_format.SetMeasurableCharacterRanges(ranges);

            Region[] regions = TextRenderer.MeasureCharacterRanges(Text,
                                                                   ThemeEngine.Current.GetLinkFont(this),
                                                                   PaddingClientRectangle,
                                                                   string_format);

            for (int i = 0; i < pieces.Length; i++)
            {
                pieces[i].region = regions[i];
                pieces[i].region.Translate(Padding.Left, Padding.Top);
            }

            Invalidate();
        }
Exemplo n.º 15
0
        /// <summary>
        /// Measures the size of the button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public override Size MeasureSize(object sender, RibbonElementMeasureSizeEventArgs e)
        {
            if (!Visible && !Owner.IsDesignMode())
            {
                SetLastMeasuredSize(new Size(0, 0));
                return(LastMeasuredSize);
            }

            RibbonElementSizeMode theSize = GetNearestSize(e.SizeMode);
            int widthSum    = Owner.ItemMargin.Horizontal;
            int heightSum   = Owner.ItemMargin.Vertical;
            int largeHeight = OwnerPanel == null ? 0 : OwnerPanel.ContentBounds.Height - Owner.ItemPadding.Vertical;// -Owner.ItemMargin.Vertical; //58;

            Size simg = SmallImage != null ? SmallImage.Size : Size.Empty;
            Size img  = Image != null ? Image.Size : Size.Empty;
            Size sz   = Size.Empty;

            switch (theSize)
            {
            case RibbonElementSizeMode.Large:
            case RibbonElementSizeMode.Overflow:
                sz = MeasureStringLargeSize(e.Graphics, Text, Owner.Font);
                if (!string.IsNullOrEmpty(Text))
                {
                    widthSum += Math.Max(sz.Width + 1, img.Width);
                    //Got off the patch site from logicalerror
                    //heightSum = largeHeight;
                    heightSum = Math.Max(0, largeHeight);
                }
                else
                {
                    widthSum  += img.Width;
                    heightSum += img.Height;
                }

                break;

            case RibbonElementSizeMode.DropDown:
                sz = TextRenderer.MeasureText(Text, Owner.Font);
                if (!string.IsNullOrEmpty(Text))
                {
                    widthSum += sz.Width + 1;
                }
                widthSum  += simg.Width + Owner.ItemMargin.Horizontal;
                heightSum += Math.Max(sz.Height, simg.Height);
                heightSum += 2;
                break;

            case RibbonElementSizeMode.Medium:
                sz = TextRenderer.MeasureText(Text, Owner.Font);
                if (!string.IsNullOrEmpty(Text))
                {
                    widthSum += sz.Width + 1;
                }
                widthSum  += simg.Width + Owner.ItemMargin.Horizontal;
                heightSum += Math.Max(sz.Height, simg.Height);
                break;

            case RibbonElementSizeMode.Compact:
                widthSum  += simg.Width;
                heightSum += simg.Height;
                break;

            default:
                throw new ApplicationException("SizeMode not supported: " + e.SizeMode.ToString());
            }

            //if (theSize == RibbonElementSizeMode.DropDown)
            //{
            //   heightSum += 2;
            //}
            switch (Style)
            {
            case RibbonButtonStyle.DropDown:
            case RibbonButtonStyle.SplitDropDown:  // drawing size calculation for DropDown and SplitDropDown is identical
                widthSum += arrowWidth + _dropDownMargin.Horizontal;
                break;

            case RibbonButtonStyle.DropDownListItem:
                break;
            }

            //check the minimum and mazimum size properties but only in large mode
            if (theSize == RibbonElementSizeMode.Large)
            {
                //Minimum Size
                if (MinimumSize.Height > 0 && heightSum < MinimumSize.Height)
                {
                    heightSum = MinimumSize.Height;
                }
                if (MinimumSize.Width > 0 && widthSum < MinimumSize.Width)
                {
                    widthSum = MinimumSize.Width;
                }

                //Maximum Size
                if (MaximumSize.Height > 0 && heightSum > MaximumSize.Height)
                {
                    heightSum = MaximumSize.Height;
                }
                if (MaximumSize.Width > 0 && widthSum > MaximumSize.Width)
                {
                    widthSum = MaximumSize.Width;
                }
            }

            SetLastMeasuredSize(new Size(widthSum, heightSum));

            return(LastMeasuredSize);
        }
Exemplo n.º 16
0
        private void CalculateInternalLayoutMetrics()
        {
            Size empty            = Size.Empty;
            Size alignThis        = Size.Empty;
            Size defaultImageSize = ToolStripDropDownMenu.defaultImageSize;
            Size size             = Size.Empty;
            Size size5            = Size.Empty;

            for (int i = 0; i < this.Items.Count; i++)
            {
                ToolStripItem     item  = this.Items[i];
                ToolStripMenuItem item2 = item as ToolStripMenuItem;
                if (item2 != null)
                {
                    Size textSize = item2.GetTextSize();
                    if (item2.ShowShortcutKeys)
                    {
                        Size shortcutTextSize = item2.GetShortcutTextSize();
                        if (this.tabWidth == -1)
                        {
                            this.tabWidth = TextRenderer.MeasureText("\t", this.Font).Width;
                        }
                        textSize.Width += this.tabWidth + shortcutTextSize.Width;
                        textSize.Height = Math.Max(textSize.Height, shortcutTextSize.Height);
                    }
                    empty.Width  = Math.Max(empty.Width, textSize.Width);
                    empty.Height = Math.Max(empty.Height, textSize.Height);
                    Size size8 = Size.Empty;
                    if (item2.Image != null)
                    {
                        size8 = (item2.ImageScaling == ToolStripItemImageScaling.SizeToFit) ? base.ImageScalingSize : item2.Image.Size;
                    }
                    alignThis.Width  = Math.Max(alignThis.Width, size8.Width);
                    alignThis.Height = Math.Max(alignThis.Height, size8.Height);
                    if (item2.CheckedImage != null)
                    {
                        Size size9 = item2.CheckedImage.Size;
                        defaultImageSize.Width  = Math.Max(size9.Width, defaultImageSize.Width);
                        defaultImageSize.Height = Math.Max(size9.Height, defaultImageSize.Height);
                    }
                }
                else if (!(item is ToolStripSeparator))
                {
                    size5.Height = Math.Max(item.Bounds.Height, size5.Height);
                    size5.Width  = Math.Max(item.Bounds.Width, size5.Width);
                }
            }
            this.maxItemSize.Height = Math.Max(empty.Height + TextPadding.Vertical, Math.Max((int)(defaultImageSize.Height + CheckPadding.Vertical), (int)(size.Height + ArrowPadding.Vertical)));
            if (this.ShowImageMargin)
            {
                this.maxItemSize.Height = Math.Max(alignThis.Height + ImagePadding.Vertical, this.maxItemSize.Height);
            }
            if (this.ShowCheckMargin)
            {
                int num1 = defaultImageSize.Width;
            }
            if (this.ShowImageMargin)
            {
                int num6 = alignThis.Width;
            }
            size                    = new Size(10, this.maxItemSize.Height);
            empty.Height            = this.maxItemSize.Height - TextPadding.Vertical;
            alignThis.Height        = this.maxItemSize.Height - ImagePadding.Vertical;
            defaultImageSize.Height = this.maxItemSize.Height - CheckPadding.Vertical;
            empty.Width             = Math.Max(empty.Width, size5.Width);
            Point location = Point.Empty;
            int   width    = 0;
            int   num3     = Math.Max(0, alignThis.Width - ToolStripDropDownMenu.defaultImageSize.Width);

            if (this.ShowCheckMargin && this.ShowImageMargin)
            {
                width               = DefaultImageAndCheckMarginWidth + num3;
                location            = new Point(CheckPadding.Left, CheckPadding.Top);
                this.checkRectangle = LayoutUtils.Align(defaultImageSize, new Rectangle(location.X, location.Y, defaultImageSize.Width, this.maxItemSize.Height), ContentAlignment.MiddleCenter);
                location.X          = (this.checkRectangle.Right + CheckPadding.Right) + ImagePadding.Left;
                location.Y          = ImagePadding.Top;
                this.imageRectangle = LayoutUtils.Align(alignThis, new Rectangle(location.X, location.Y, alignThis.Width, this.maxItemSize.Height), ContentAlignment.MiddleCenter);
            }
            else if (this.ShowCheckMargin)
            {
                width               = DefaultImageMarginWidth;
                location            = new Point(1, CheckPadding.Top);
                this.checkRectangle = LayoutUtils.Align(defaultImageSize, new Rectangle(location.X, location.Y, width, this.maxItemSize.Height), ContentAlignment.MiddleCenter);
                this.imageRectangle = Rectangle.Empty;
            }
            else if (this.ShowImageMargin)
            {
                width               = DefaultImageMarginWidth + num3;
                location            = new Point(1, CheckPadding.Top);
                this.checkRectangle = LayoutUtils.Align(LayoutUtils.UnionSizes(defaultImageSize, alignThis), new Rectangle(location.X, location.Y, width - 1, this.maxItemSize.Height), ContentAlignment.MiddleCenter);
                this.imageRectangle = this.checkRectangle;
            }
            else
            {
                width = 0;
            }
            location.X             = width + 1;
            this.imageMarginBounds = new Rectangle(0, 0, width, base.Height);
            location.X             = this.imageMarginBounds.Right + TextPadding.Left;
            location.Y             = TextPadding.Top;
            this.textRectangle     = new Rectangle(location, empty);
            location.X             = (this.textRectangle.Right + TextPadding.Right) + ArrowPadding.Left;
            location.Y             = ArrowPadding.Top;
            this.arrowRectangle    = new Rectangle(location, size);
            this.maxItemSize.Width = (this.arrowRectangle.Right + ArrowPadding.Right) - this.imageMarginBounds.Left;
            base.Padding           = this.DefaultPadding;
            int num4 = this.imageMarginBounds.Width;

            if (this.RightToLeft == RightToLeft.Yes)
            {
                num4 += TextPadding.Right;
                int num5 = this.maxItemSize.Width;
                this.checkRectangle.X    = num5 - this.checkRectangle.Right;
                this.imageRectangle.X    = num5 - this.imageRectangle.Right;
                this.textRectangle.X     = num5 - this.textRectangle.Right;
                this.arrowRectangle.X    = num5 - this.arrowRectangle.Right;
                this.imageMarginBounds.X = num5 - this.imageMarginBounds.Right;
            }
            else
            {
                num4 += TextPadding.Left;
            }
            this.maxItemSize.Height          += this.maxItemSize.Height % 2;
            this.textRectangle.Y              = LayoutUtils.VAlign(this.textRectangle.Size, new Rectangle(Point.Empty, this.maxItemSize), ContentAlignment.MiddleCenter).Y;
            this.textRectangle.Y             += this.textRectangle.Height % 2;
            this.state[stateMaxItemSizeValid] = true;
            this.PaddingToTrim = num4;
        }
Exemplo n.º 17
0
 /// <include file='doc\DrawListViewItemEventArgs.uex' path='docs/doc[@for="DrawListViewItemEventArgs.DrawText1"]/*' />
 /// <devdoc>
 ///     Draws the item's text (overloaded) - useful only when View != View.Details - takes a TextFormatFlags argument.
 /// </devdoc>
 public void DrawText(TextFormatFlags flags)
 {
     TextRenderer.DrawText(graphics, item.Text, item.Font, UpdateBounds(bounds, true /*drawText*/), item.ForeColor, flags);
 }
Exemplo n.º 18
0
        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
        {
            if (text == null)
            {
                text = "";
            }

            if (caption == null)
            {
                caption = "";
            }

            // ensure we are always in a known state
            _state = DialogResult.None;

            // convert to nice wrapped lines.
            text = AddNewLinesToText(text);
            // get pixel width and height
            Size textSize = TextRenderer.MeasureText(text, SystemFonts.DefaultFont);

            // allow for icon
            if (icon != MessageBoxIcon.None)
            {
                textSize.Width += SystemIcons.Question.Width;
            }

            var msgBoxFrm = new Form
            {
                FormBorderStyle = FormBorderStyle.FixedDialog,
                ShowInTaskbar   = false,
                StartPosition   = FormStartPosition.CenterScreen,
                Text            = caption,
                MaximizeBox     = false,
                MinimizeBox     = false,
                Width           = textSize.Width + 50,
                Height          = textSize.Height + 100,
                TopMost         = true,
            };

            Rectangle screenRectangle = msgBoxFrm.RectangleToScreen(msgBoxFrm.ClientRectangle);
            int       titleHeight     = screenRectangle.Top - msgBoxFrm.Top;

            var lblMessage = new Label
            {
                Left   = 58,
                Top    = 15,
                Width  = textSize.Width + 10,
                Height = textSize.Height + 10,
                Text   = text
            };

            msgBoxFrm.Controls.Add(lblMessage);

            var actualIcon = getMessageBoxIcon(icon);

            if (actualIcon == null)
            {
                lblMessage.Location = new Point(FORM_X_MARGIN, FORM_Y_MARGIN);
            }
            else
            {
                var iconPbox = new PictureBox
                {
                    Image    = actualIcon.ToBitmap(),
                    Location = new Point(FORM_X_MARGIN, FORM_Y_MARGIN)
                };
                msgBoxFrm.Controls.Add(iconPbox);
            }


            AddButtonsToForm(msgBoxFrm, buttons);

            // display even if theme fails
            try
            {
                ThemeManager.ApplyThemeTo(msgBoxFrm);
            }
            catch { }

            if (System.Windows.Forms.Application.OpenForms.Count > 0)
            {
                msgBoxFrm.StartPosition = FormStartPosition.Manual;
                Form parentForm = System.Windows.Forms.Application.OpenForms[0];
                // center of first form
                msgBoxFrm.Location = new Point(parentForm.Location.X + parentForm.Width / 2 - msgBoxFrm.Width / 2,
                                               parentForm.Location.Y + parentForm.Height / 2 - msgBoxFrm.Height / 2);
                DialogResult test = msgBoxFrm.ShowDialog();
            }
            else
            {
                DialogResult test = msgBoxFrm.ShowDialog();
            }

            DialogResult answer = _state;

            return(answer);
        }
Exemplo n.º 19
0
        private void DrawObjects(Graphics g, List <Map.Object> objects, bool shadow = false)
        {
            Pen pen; PointF center, ptf, topLeft;

            ThingDb.Thing tt;

            Map.Object underCursor = null;

            if (MapInterface.CurrentMode == EditMode.OBJECT_SELECT || MainWindow.Instance.mapView.picking)
            {
                underCursor = MainWindow.Instance.mapView.GetObjectUnderCursor();
            }



            if (mapRenderer.proDefault && underCursor == null)
            {
                MainWindow.Instance.mapView.mapPanel.Cursor = Cursors.Default;
            }



            bool drawExtents3D = EditorSettings.Default.Draw_Extents_3D;

            if (EditorSettings.Default.Draw_Objects)
            {
                foreach (Map.Object oe in objects)
                {
                    var customRender = oe as CustomRenderObject;
                    if (customRender != null)
                    {
                        customRender.Render(g);
                        continue;
                    }

                    ptf = oe.Location;
                    float x = ptf.X, y = ptf.Y;
                    tt = ThingDb.Things[oe.Name];

                    center  = new PointF(x, y);
                    topLeft = new PointF(center.X - objectSelectionRadius, center.Y - objectSelectionRadius);
                    pen     = mapRenderer.ColorLayout.Objects;



                    // Object facing helper
                    if (EditorSettings.Default.Draw_ObjectFacing)
                    {
                        float deg = -1F;
                        if (tt.Xfer == "MonsterXfer")
                        {
                            MonsterXfer xfer = oe.GetExtraData <MonsterXfer>();
                            deg = (float)MonsterXfer.NOX_DIRECT_VALS[xfer.DirectionId] / 256F * 360F;
                        }
                        if (tt.Xfer == "NPCXfer")
                        {
                            NPCXfer xfer = oe.GetExtraData <NPCXfer>();
                            deg = (float)MonsterXfer.NOX_DIRECT_VALS[xfer.DirectionId] / 256F * 360F;
                        }
                        if (deg >= 0F)
                        {
                            using (var m = new System.Drawing.Drawing2D.Matrix())
                            {
                                m.RotateAt(deg, center);
                                g.Transform = m;

                                g.DrawLine(objMoveablePen, center.X, center.Y, center.X + 20, center.Y);
                                g.ResetTransform();
                            }
                        }
                        // Sentry ray
                        if (tt.Xfer == "SentryXfer")
                        {
                            SentryXfer sentry = oe.GetExtraData <SentryXfer>();
                            float      targX  = x + ((float)Math.Cos(sentry.BasePosRadian) * 80F);
                            float      targY  = y + ((float)Math.Sin(sentry.BasePosRadian) * 80F);
                            // show sentry ray direction
                            g.DrawLine(sentryPen, x, y, targX, targY);
                        }
                    }

                    // invisible triggers and pressure plates
                    if (tt.DrawType == "TriggerDraw" || tt.DrawType == "PressurePlateDraw")
                    {
                        if (shadow)
                        {
                            DrawObjectExtent(g, oe, drawExtents3D);
                        }
                        //else
                        //    DrawTriggerExtent(g, oe, underCursor);
                        continue;
                    }
                    // black powder

                    if (EditorSettings.Default.Edit_PreviewMode)         // Visual Preview
                    {
                        if (tt.DrawType == "BlackPowderDraw")
                        {
                            /* Rectangle bp = new Rectangle((int)x - 2, (int)y - 2, 4, 4);
                             * g.FillRectangle(new SolidBrush(Color.Gray), bp);*/
                            continue;
                        }
                        if (tt.Xfer == "InvisibleLightXfer")
                        {
                            /*bool isUnderCursor = false;
                             *
                             * Pen Penlight = new Pen(Color.Yellow, 1);
                             * if (underCursor != null) isUnderCursor = underCursor.Equals(oe);
                             *
                             * if (isUnderCursor)
                             *  Penlight = new Pen(Color.Orange, 1);
                             *
                             * bool isSelected = mapRenderer.SelectedObjects.Items.Contains(oe);
                             * bool isSelected2 = MapInterface.RecSelected.Contains(oe);
                             * if (isSelected && isSelected2 && MapInterface.KeyHelper.ShiftKey)
                             * {
                             *  isSelected = false;
                             *  isSelected2 = false;
                             * }
                             *
                             *
                             * if (isSelected || isSelected2)
                             * {
                             *  Penlight = Pens.DarkOrange;
                             *  if (mapRenderer.proHand && isUnderCursor)
                             *      MainWindow.Instance.mapView.mapPanel.Cursor = Cursors.Hand;
                             *
                             * }
                             *
                             * g.DrawEllipse(Penlight, new RectangleF(center.X - 9, center.Y - 9, 18, 18));
                             * g.DrawEllipse(Penlight, new RectangleF(center.X - 13, center.Y - 13, 26, 26));
                             * g.DrawEllipse(Penlight, new RectangleF(center.X - 17, center.Y - 17, 34, 34));
                             */
                            continue;
                        }

                        Bitmap image = GetObjectImage(oe, shadow);

                        /*if (tt.Name.StartsWith("Amb") && image == null)
                         * {
                         *  image = mapRenderer.VideoBag.GetBitmap(tt.SpriteMenuIcon);
                         *  drawOffsetX = 82;
                         *  drawOffsetY = 122;
                         * }*/

                        if (image == null || tt.DrawType == "NoDraw")
                        {
                            // in case of failure draw only the extent
                            //DrawObjectExtent(g, oe, drawExtents3D);
                        }
                        else
                        {
                            int sizeX = tt.SizeX / 2;
                            int sizeY = tt.SizeY / 2;
                            x -= (sizeX - drawOffsetX);
                            y -= (sizeY - drawOffsetY) + tt.Z;
                            // no blurring
                            int ix = Convert.ToInt32(x);
                            int iy = Convert.ToInt32(y);

                            // recolor in case it is being selected
                            bool isSelected  = mapRenderer.SelectedObjects.Items.Contains(oe);
                            bool isSelected2 = MapInterface.RecSelected.Contains(oe);


                            if (isSelected && isSelected2 && MapInterface.KeyHelper.ShiftKey)
                            {
                                isSelected  = false;
                                isSelected2 = false;
                            }
                            bool isUnderCursor = false;
                            if (underCursor != null)
                            {
                                isUnderCursor = underCursor.Equals(oe);
                            }
                            // draw the image
                            if (isSelected || isUnderCursor || shadow || isSelected2)
                            {
                                // highlight selection
                                var shader = new BitmapShader(image);
                                shader.LockBitmap();

                                var hltColor = mapRenderer.ColorLayout.Selection;

                                if (isSelected || isSelected2)
                                {
                                    if (mapRenderer.proHand && isUnderCursor)
                                    {
                                        MainWindow.Instance.mapView.mapPanel.Cursor = Cursors.Hand;
                                    }



                                    shader.ColorShade(hltColor, 0.5F);
                                }
                                else if (isUnderCursor)
                                {
                                    hltColor = Color.PaleGreen;
                                    if (MapInterface.CurrentMode == EditMode.OBJECT_PLACE && !MainWindow.Instance.mapView.picking)
                                    {
                                        hltColor = mapRenderer.ColorLayout.Removing;
                                    }

                                    shader.ColorGradWaves(hltColor, 7F, Environment.TickCount);
                                }
                                if (shadow)
                                {
                                    shader.MakeSemitransparent(165);
                                }

                                image = shader.UnlockBitmap();

                                g.DrawImage(image, ix, iy, image.Width, image.Height);
                                image.Dispose();
                            }
                            else
                            {
                                g.DrawImage(image, ix, iy, image.Width, image.Height);
                            }
                        }
                    }
                    else
                    {
                        if (mapRenderer.SelectedObjects.Items.Contains(oe))
                        {
                            pen = Pens.Green;
                        }
                        if (MapInterface.RecSelected.Contains(oe))
                        {
                            pen = Pens.Green;
                        }
                        if ((mapRenderer.SelectedObjects.Items.Contains(oe) && MapInterface.RecSelected.Contains(oe)))
                        {
                            pen = mapRenderer.ColorLayout.Objects;
                        }

                        g.DrawEllipse(pen, new RectangleF(topLeft, new Size(2 * objectSelectionRadius, 2 * objectSelectionRadius)));//55

                        // If is a door
                        if ((tt.Class & ThingDb.Thing.ClassFlags.DOOR) == ThingDb.Thing.ClassFlags.DOOR)
                        {
                            DoorXfer door = oe.GetExtraData <DoorXfer>();
                            if (door.Direction == DoorXfer.DOORS_DIR.South)
                            {
                                g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y), new Point((int)center.X - 20, (int)center.Y - 20));

                                if (drawExtents3D)
                                {
                                    g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y - 40), new Point((int)center.X - 20, (int)center.Y - 60));
                                    g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y), new Point((int)center.X - 20, (int)center.Y - 60));

                                    g.DrawLine(doorPen, new Point((int)center.X - 20, (int)center.Y - 20), new Point((int)center.X - 20, (int)center.Y - 60));
                                }
                            }
                            else if (door.Direction == DoorXfer.DOORS_DIR.West)
                            {
                                g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y), new Point((int)center.X + 20, (int)center.Y - 20));

                                if (drawExtents3D)
                                {
                                    g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y - 40), new Point((int)center.X + 20, (int)center.Y - 60));
                                    g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y), new Point((int)center.X + 20, (int)center.Y - 60));

                                    g.DrawLine(doorPen, new Point((int)center.X + 20, (int)center.Y - 20), new Point((int)center.X + 20, (int)center.Y - 60));
                                }
                            }
                            else if (door.Direction == DoorXfer.DOORS_DIR.North)
                            {
                                g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y), new Point((int)center.X + 20, (int)center.Y + 20));

                                if (drawExtents3D)
                                {
                                    g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y - 40), new Point((int)center.X + 20, (int)center.Y - 20));
                                    g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y), new Point((int)center.X + 20, (int)center.Y - 20));

                                    g.DrawLine(doorPen, new Point((int)center.X + 20, (int)center.Y + 20), new Point((int)center.X + 20, (int)center.Y - 20));
                                }
                            }
                            else if (door.Direction == DoorXfer.DOORS_DIR.East)
                            {
                                g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y), new Point((int)center.X - 20, (int)center.Y + 20));

                                if (drawExtents3D)
                                {
                                    g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y - 40), new Point((int)center.X - 20, (int)center.Y - 20));
                                    g.DrawLine(doorPen, new Point((int)center.X, (int)center.Y), new Point((int)center.X - 20, (int)center.Y - 20));

                                    g.DrawLine(doorPen, new Point((int)center.X - 20, (int)center.Y + 20), new Point((int)center.X - 20, (int)center.Y - 20));
                                }
                            }
                        }
                    }

                    if (EditorSettings.Default.Draw_Extents)
                    {
                        if (!(!EditorSettings.Default.Draw_AllExtents && oe.HasFlag(ThingDb.Thing.FlagsFlags.NO_COLLIDE)))
                        {
                            DrawObjectExtent(g, oe, drawExtents3D);
                        }
                    }
                }

                // Draw labels on the separate cycle to prevent layer glitching
                if (EditorSettings.Default.Draw_AllText)
                {
                    foreach (Map.Object oe in objects)
                    {
                        Point textLocaton = new Point(Convert.ToInt32(oe.Location.X), Convert.ToInt32(oe.Location.Y));
                        textLocaton.X -= objectSelectionRadius; textLocaton.Y -= objectSelectionRadius;

                        if (EditorSettings.Default.Draw_ObjCustomLabels && oe.Team > 0)
                        {
                            // Draw team
                            Point loc = new Point(textLocaton.X, textLocaton.Y - 12);
                            TextRenderer.DrawText(g, String.Format(FORMAT_OBJECT_TEAM, oe.Team), objectExtentFont, loc, Color.LightPink);
                        }
                        if (EditorSettings.Default.Draw_ObjCustomLabels && oe.Scr_Name.Length > 0)
                        {
                            // Draw custom label
                            Size size = TextRenderer.MeasureText(oe.ScrNameShort, objectExtentFont);
                            textLocaton.X -= size.Width / 3;
                            TextRenderer.DrawText(g, oe.ScrNameShort, objectExtentFont, textLocaton, Color.Cyan);
                        }
                        else if (EditorSettings.Default.Draw_ObjThingNames)
                        {
                            // Draw thing name
                            Size size = TextRenderer.MeasureText(oe.Name, objectExtentFont);
                            textLocaton.X -= size.Width / 3;
                            TextRenderer.DrawText(g, oe.Name, objectExtentFont, textLocaton, Color.Green);
                        }
                        else if (!EditorSettings.Default.Edit_PreviewMode && oe.Extent >= 0 && !(EditorSettings.Default.Draw_Extents || EditorSettings.Default.Draw_AllExtents))
                        {
                            TextRenderer.DrawText(g, oe.Extent.ToString(), objectExtentFont, textLocaton, Color.Purple);
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
 public void DrawText(TextFormatFlags flags)
 {
     TextRenderer.DrawText(Graphics, Item.Text, Item.Font, UpdateBounds(Bounds, drawText: true), Item.ForeColor, flags);
 }