本文代码主要是参考别人的,仅为个人记录,方面后续使用~
效果图:
主要代码在一个Win32Utility类中,代码如下:
public static class Win32Utility
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); [DllImport("user32.dll")]
private static extern bool SendMessage(IntPtr hwnd, int msg, int wParam, StringBuilder lParam); [DllImport("user32.dll")]
private static extern bool GetComboBoxInfo(IntPtr hwnd, ref COMBOBOXINFO pcbi); [StructLayout(LayoutKind.Sequential)]
private struct COMBOBOXINFO
{
public int cbSize;
public RECT rcItem;
public RECT rcButton;
public IntPtr stateButton;
public IntPtr hwndCombo;
public IntPtr hwndItem;
public IntPtr hwndList;
} [StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
} private const int EM_SETCUEBANNER = 0x1501;
private const int EM_GETCUEBANNER = 0x1502; //本文地址:http://www.cnblogs.com/Interkey/p/HintText.html public static void SetCueText(Control control, string text)
{
if (control is ComboBox)
{
COMBOBOXINFO info = GetComboBoxInfo(control);
SendMessage(info.hwndItem, EM_SETCUEBANNER, , text);
}
else
{
SendMessage(control.Handle, EM_SETCUEBANNER, , text);
}
} private static COMBOBOXINFO GetComboBoxInfo(Control control)
{
COMBOBOXINFO info = new COMBOBOXINFO();
//a combobox is made up of three controls, a button, a list and textbox;
//we want the textbox
info.cbSize = Marshal.SizeOf(info);
GetComboBoxInfo(control.Handle, ref info);
return info;
} public static string GetCueText(Control control)
{
StringBuilder builder = new StringBuilder();
if (control is ComboBox)
{
COMBOBOXINFO info = new COMBOBOXINFO();
//a combobox is made up of two controls, a list and textbox;
//we want the textbox
info.cbSize = Marshal.SizeOf(info);
GetComboBoxInfo(control.Handle, ref info);
SendMessage(info.hwndItem, EM_GETCUEBANNER, , builder);
}
else
{
SendMessage(control.Handle, EM_GETCUEBANNER, , builder);
}
return builder.ToString();
}
}
本文地址:http://www.cnblogs.com/Interkey/p/HintText.html
使用时,如以下代码即可,只不过仅限在少数控件上(主要用在TextBox上,当然也可以用在ComboBox上,不过有限制)
Win32Utility.SetCueText(this.tb_UserName, "请输入用户名");
Win32Utility.SetCueText(this.tb_Password, "请输入密码");
Win32Utility.SetCueText(this.tb_ConfigPassword, "请输入确认密码");
Win32Utility.SetCueText(this.tb_Email, "请输入邮箱"); //Win32Utility.SetCueText(this.richTextBox1, "123456");//设置其他控件无效 //this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;//在这种样式下无效
Win32Utility.SetCueText(this.comboBox1, "请选择");
以上即可实现效果,不过在此提供了相应代码下载;
本文参考了以下文章:
C#/WinForm给控件加入hint文字
C# TextBox with Outlook 2007-style prompt