将占位符添加到密码c# winforms的文本框控件

问题描述 投票:0回答:4

如何向c# winform控件添加占位符?

当控件失去焦点且控件文本为

null
时,我希望出现占位符。

当文本框为

UsePasswordChar true
时,它仍然显示占位符(以明文形式),并且当用户开始写入时,它显示密码字符。

有什么想法吗?

c# winforms textbox placeholder
4个回答
4
投票

如果您正在使用 WinForms for .NET Core,或者计划将来进行迁移,则可以使用 TextBox 的新 PlaceholderText 属性。它大大简化了事情。


0
投票

我对 WinForms 的经验不是很丰富,但我怀疑您可以使用

GotFocus
事件根据控件是否有值来将类型更改为密码或从密码更改为密码。

这应该为您指明正确的方向:https://msdn.microsoft.com/en-us/library/system.windows.forms.control.gotfocus(v=vs.110).aspx


0
投票

您可以为lostFocus和AddFocus添加事件

Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";

myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
myTxtbx.LostFocus += LostFocus.EventHandle(AddText);

public void RemoveText(object sender, EventArgs e)
{
     myTxtbx.Text = "";
}

public void AddText(object sender, EventArgs e)
{
     if(String.IsNullOrWhiteSpace(myTxtbx.Text))
        myTxtbx.Text = "Enter text here...";
}

或者您可以创建一个带有提示的新类,请在此处查看此答案: 回答


0
投票

GotFocus LostFocus 无法按预期工作,您需要设置提示横幅。

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace PlaceHolderTextBox
{
    public class PlaceHolderTextBox : TextBox
    {
        private string placeholderText = string.Empty;
        private const int EM_SETCUEBANNER = 0x1501;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern bool MessageBeep(uint type);
        public PlaceHolderTextBox() : base() 
        { 

        }
        [Localizable(true)]
        [DefaultValue("")]
        [Description("")]
        public virtual string PlaceholderText
        {
            get
            {
                return placeholderText;
            }
            set
            {
                if (value is null)
                {
                    value = string.Empty;
                }

                if (placeholderText != value)
                {
                    placeholderText = value;
                    if (IsHandleCreated)
                    {
                        Invalidate();
                        SetPlaceholderText();
                    }
                }
            }
        }

        protected override void OnCreateControl()
        {
            base.OnCreateControl();
            SetPlaceholderText();
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern Int32 SendMessage
      (IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
        public void SetPlaceholderText()
        {
            SendMessage(this.Handle, EM_SETCUEBANNER, 0, placeholderText);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.