GDI+中如何实现仅按下Alt键时才显示HotKeyPrefix下划线?
Absolutely—you can replicate the default Button's behavior where hotkey underlines only appear when the Alt key is pressed. The trick is to leverage the system's built-in UI state tracking and adjust your text rendering based on that state, plus handle the window messages that trigger state changes.
Here's a complete implementation for your custom button:
public class CustomButton : Button { protected override void OnPaint(PaintEventArgs e) { // Skip base.OnPaint if you're fully customizing the button's appearance // base.OnPaint(e); // Set up text alignment to match the default button's centering TextFormatFlags textFlags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter; // Toggle underline visibility based on whether keyboard cues are active (Alt key pressed) if (ShowKeyboardCues) { textFlags |= TextFormatFlags.ShowPrefix; // Show the &-specified underline } else { textFlags |= TextFormatFlags.HidePrefix; // Hide the underline } // Draw the text with the appropriate flags TextRenderer.DrawText( e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, this.BackColor, textFlags ); } protected override void WndProc(ref Message m) { const int WM_UPDATEUISTATE = 0x0128; const int WM_CHANGEUISTATE = 0x0127; switch (m.Msg) { // These messages indicate the system's keyboard cue state has changed case WM_UPDATEUISTATE: case WM_CHANGEUISTATE: // Let the base control handle the state update first base.WndProc(ref m); // Force a redraw to reflect the new underline state Invalidate(); break; default: base.WndProc(ref m); break; } } }
Key Details:
ShowKeyboardCuesProperty: This built-inControlproperty automatically tracks whether the system should display keyboard navigation cues (like hotkey underlines). It updates when the Alt key is pressed/released.TextFormatFlags: We useShowPrefixto render the underline for the&-marked character when cues are active, andHidePrefixto hide it otherwise. This matches exactly how the default Button renders text.- Window Messages: The
WM_UPDATEUISTATEandWM_CHANGEUISTATEmessages are sent when the system's UI state changes. We overrideWndProcto catch these, let the base control update its state, then trigger a redraw so our custom paint logic picks up the newShowKeyboardCuesvalue.
If you're already drawing other parts of the button (like borders or backgrounds), just integrate the text rendering part into your existing OnPaint code—it'll work seamlessly with your custom visuals.
内容的提问来源于stack exchange,提问作者Jonas Kohl
相关产品推荐
相关产品推荐

