Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to always show underline character? (C# Windows Form)

I'm making a dialog that look like Notepad's Find Dialog. I notice that the underline character of Notepad's Find dialog always show all the time (I have to press ALT key to see this with my dialog). How to always show underline character like that?

I try to use SendKeys.Send("%") on Form_Load event but nothing happens.

There is another problem, when I press ALT key on child Form, it show underline charater of parent Form too. How to avoid that?

This is sreenshot of Notepad's find dialog: enter image description here

I pretty sure this is not about Ease of Acess Center, because the main Form of Notepad doesn't always show this.

like image 570
Ryan Avatar asked Oct 30 '22 23:10

Ryan


1 Answers

Seeing the n in "Find" underlined in the Notepad dialog is an intentional bug. The dialog isn't actually part of Notepad, it built into Windows. Underlying winapi call is FindText(). The feature is in general a pile 'o bugs, one core problem is that creating a new window after the UI is put in the "show underlines" state doesn't work correctly, that new window isn't also in that state. Presumably the intentional bug was based on the assumption that the user would be somewhat likely to use the Alt key to get the dialog displayed. Yuck if he pressed Ctrl+F.

The Windows dialog probably does it by simply drawing the "Find" string with DrawText() with the DT_NOPREFIX option omitted. You could do the same with TextRenderer.DrawText(), omit the TextFormatFlags.HidePrefix option.

Not exactly WinFormsy, you'd favor a Label control instead of code. It is hackable, you'd have to intentionally send the message that puts the UI in the "show underlines" state for your own dialog. Do so in an override for the OnHandleCreated() method:

    protected override void OnHandleCreated(EventArgs e) {
        const int WM_UPDATEUISTATE = 0x0128;
        base.OnHandleCreated(e);
        SendMessage(this.label1.Handle, WM_UPDATEUISTATE, new IntPtr(0x30002), IntPtr.Zero);
    }
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

Where "label1" is the control you want to show underlines. Repeat for other controls, if any. It is supposed to work by sending the message to the form, that this doesn't work is part of the pile 'o bugs. Yuck.

Fwiw: do not fix this by changing the system option as recommended in the duplicate. That's very unreasonable.

like image 181
Hans Passant Avatar answered Nov 08 '22 09:11

Hans Passant