You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows Forms按钮文本中快捷键对应字母高亮实现咨询

Got it, let's figure out how to highlight that shortcut key in your WinForms Button. The default WinForms behavior only shows the underlined shortcut letter when the Alt key is pressed, but we can make it visible permanently with custom owner-drawn logic. Here's a straightforward implementation:

Step 1: Enable Owner-Draw Mode for the Button

First, you need to tell the button that we'll handle its drawing manually. You can do this either in the Visual Studio Designer (set the DrawMode property to OwnerDrawFixed) or in code:

public YourFormName()
{
    InitializeComponent();
    // Target your button control here
    myButton.DrawMode = ButtonDrawMode.OwnerDrawFixed;
    myButton.DrawItem += MyButton_DrawItem;
}
Step 2: Handle the DrawItem Event to Customize Text Rendering

Next, we'll write the logic to parse the button's text (looking for the & prefix that defines the shortcut), split the text, and draw the shortcut letter with a highlight (like an underline, bold, or custom color—we'll use underline as the example):

private void MyButton_DrawItem(object sender, DrawItemEventArgs e)
{
    Button targetBtn = sender as Button;
    if (targetBtn == null) return;

    // Parse the button text to find the shortcut character
    string originalText = targetBtn.Text;
    int ampersandPos = originalText.IndexOf('&');
    string displayText = originalText.Replace("&", "");
    int shortcutCharIndex = -1;

    // Validate the & position (it shouldn't be the last character)
    if (ampersandPos != -1 && ampersandPos < originalText.Length - 1)
    {
        shortcutCharIndex = ampersandPos;
        // Adjust if the & was at the end of the original text
        if (shortcutCharIndex == displayText.Length)
            shortcutCharIndex = -1;
    }

    // Draw the button's background and focus rectangle first
    e.DrawBackground();
    if ((e.State & DrawItemState.Focus) == DrawItemState.Focus)
        e.DrawFocusRectangle();

    // Set up text styles and colors (handle disabled state too)
    Font regularFont = targetBtn.Font;
    Font shortcutFont = new Font(regularFont, FontStyle.Underline); // Highlight with underline
    Color textColor = targetBtn.ForeColor;
    if ((e.State & DrawItemState.Disabled) == DrawItemState.Disabled)
        textColor = SystemColors.GrayText;

    // Center-align text (matches default button behavior)
    StringFormat textFormat = new StringFormat();
    textFormat.Alignment = StringAlignment.Center;
    textFormat.LineAlignment = StringAlignment.Center;
    textFormat.HotkeyPrefix = HotkeyPrefix.None; // Disable default Alt-triggered underline

    if (shortcutCharIndex == -1)
    {
        // No shortcut defined—draw the full text normally
        TextRenderer.DrawText(e.Graphics, displayText, regularFont, e.Bounds, textColor, textFormat);
    }
    else
    {
        // Split text into three parts: before shortcut, shortcut char, after shortcut
        string preShortcutText = displayText.Substring(0, shortcutCharIndex);
        char shortcutChar = displayText[shortcutCharIndex];
        string postShortcutText = shortcutCharIndex < displayText.Length - 1 
            ? displayText.Substring(shortcutCharIndex + 1) 
            : "";

        // Calculate positions to keep text centered
        SizeF preSize = e.Graphics.MeasureString(preShortcutText, regularFont);
        SizeF shortcutSize = e.Graphics.MeasureString(shortcutChar.ToString(), shortcutFont);
        float totalTextWidth = preSize.Width + shortcutSize.Width + e.Graphics.MeasureString(postShortcutText, regularFont).Width;
        float startX = e.Bounds.Left + (e.Bounds.Width - totalTextWidth) / 2;
        float startY = e.Bounds.Top + (e.Bounds.Height - preSize.Height) / 2;

        // Draw each part sequentially
        e.Graphics.DrawString(preShortcutText, regularFont, new SolidBrush(textColor), startX, startY);
        startX += preSize.Width;
        e.Graphics.DrawString(shortcutChar.ToString(), shortcutFont, new SolidBrush(textColor), startX, startY);
        startX += shortcutSize.Width;
        e.Graphics.DrawString(postShortcutText, regularFont, new SolidBrush(textColor), startX, startY);
    }
}
Customization Options
  • Change Highlight Style: Instead of underlining, you can make the shortcut bold by setting shortcutFont = new Font(regularFont, FontStyle.Bold), or use a different color by passing a custom SolidBrush (like new SolidBrush(Color.DarkBlue)) for the shortcut character.
  • Handle Multiple Shortcuts: If you have text with multiple & characters, this code will only highlight the first one (which aligns with WinForms' default shortcut behavior).
  • Consistent State Handling: The code already accounts for disabled buttons (grays out text) and focus rectangles, so it matches the default button look and feel.

内容的提问来源于stack exchange,提问作者Shaifali Goel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:04:09