Watermark TextBox in WinForms

前端 未结 10 1990
说谎
说谎 2020-11-22 00:35

Can anyone point me to a good implementation of a basic Windows Forms TextBox that will initially show watermark text that disappears when the cursor enters it? I think I ca

10条回答
  •  粉色の甜心
    2020-11-22 01:21

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);
    

    And the message constants:

    private const uint EM_SETCUEBANNER = 0x1501;
    private const uint CB_SETCUEBANNER = 0x1703;    // minimum supported client Windows Vista, minimum supported server Windows Server 2008
    

    And imho the best way to implement it is as an extension method.
    So for the TextBox control the syntax would be:

    MyTextBox.CueBanner(false, "Password");
    

    From the code:

    public static void CueBanner(this TextBox textbox, bool showcuewhenfocus, string cuetext)
    {
        uint BOOL = 0;
        if (showcuewhenfocus == true) { BOOL = 1; }
    
        SendMessage(textbox.Handle, EM_SETCUEBANNER, (IntPtr)BOOL, cuetext); ;
    }
    

提交回复
热议问题