显示C#winforms编辑控件的提示

时间:2022-05-11 00:28:55

I'm working on a C# winforms application (VS.NET 2008, .NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field the text should disappear. How can I achieve this?

我正在开发一个C#winforms应用程序(VS.NET 2008,.NET 3.5 sp 1)。我在表单上有一个搜索字段,而不是在搜索字段旁边有一个标签我想在搜索字段本身的背景中显示一些灰色文本(例如,“搜索字词”)。当用户开始在搜索字段中输入文本时,文本应该消失。我怎样才能做到这一点?

5 个解决方案

#1


9  

You will need to use some P/Inovke interop code to do this. Look for the Win32 API SendMessage function and the EM_SETCUEBANNER message.

您需要使用一些P / Inovke互操作代码来执行此操作。查找Win32 API SendMessage函数和EM_SETCUEBANNER消息。

#2


4  

Its better to post the code instead of link. I am posting this from here

最好发布代码而不是链接。我是从这里发布的

            //Copyright (c) 2008 Jason Kemp

            //Permission is hereby granted, free of charge, to any person obtaining a copy
            //of this software and associated documentation files (the "Software"), to deal
            //in the Software without restriction, including without limitation the rights
            //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
            //copies of the Software, and to permit persons to whom the Software is
            //furnished to do so, subject to the following conditions:

            //The above copyright notice and this permission notice shall be included in
            //all copies or substantial portions of the Software.

            //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
            //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
            //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
            //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
            //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
            //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
            //THE SOFTWARE.

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


            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;

                public static void SetCueText(Control control, string text)
                {
                    if (control is ComboBox)
                    {
                        COMBOBOXINFO info = GetComboBoxInfo(control);
                        SendMessage(info.hwndItem, EM_SETCUEBANNER, 0, text);
                    }
                    else
                    {
                        SendMessage(control.Handle, EM_SETCUEBANNER, 0, 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, 0, builder);
                    }
                    else
                    {
                        SendMessage(control.Handle, EM_GETCUEBANNER, 0, builder);
                    }
                    return builder.ToString();
                }
            }

#3


2  

I think the way this is generally done is to set the color of the text to gray and prefill it with your hint text.

我认为通常这样做的方法是将文本的颜色设置为灰色,并使用提示文本预填充它。

Then, write handlers for the text field's focus events, modifying the fields contents and color based when focus is gained and lost. Here's some pseudocode (sorry, it's totally not C# code. I have Actionscript on the brain right now):

然后,为文本字段的焦点事件编写处理程序,根据获得和丢失焦点时修改字段内容和颜色。这是一些伪代码(对不起,它完全不是C#代码。我现在脑部有Actionscript):

TextInput myInput;
boolean showingHint = true;

myInput.text = "Search Terms";
myInput.color = 0xcccccc;

myInput.onFocusGained = function() {
  if(showingHint) {
    myInput.text = "";
    myInput.color = 0x000000;
    showingHint = false;
  }
}

myInput.onFocusLost = function() {
  if(!showingHint && myInput.text.length == 0) {
    myInput.text = "Search Terms";
    myInput.color = 0xcccccc;
    showingHint = true;
  }
}

Remember, you only want to change the text on focus lost if the user hasn't manually changed the text. Use a separate boolean to track if you're showing the hint or not so you can differentiate between the user manually typing your "hint" text as actual content. Similarly, you only want to clear the contents of the input box if the hint is being displayed so you don't get rid of user input accidentally.

请记住,如果用户没有手动更改文本,您只想更改焦点丢失的文本。使用单独的布尔值来跟踪您是否显示提示,以便您可以区分用户手动键入“提示”文本作为实际内容。同样,如果正在显示提示,您只想清除输入框的内容,这样就不会意外地删除用户输入。

#4


1  

Give the code from this link a try. It extends the winforms functionality, as it isn't possible to achieve right out of the box. The source code is available as well. Keep in mind, it only works on Win XP or higher.

尝试从此链接中提供代码。它扩展了winforms功能,因为它无法实现开箱即用。源代码也可用。请记住,它仅适用于Win XP或更高版本。

http://www.aaronlerch.com/blog/2007/12/01/watermarked-edit-controls/

#5


0  

There is built-in functionality in the text box control -- AutoCompleteMode and AutoCompleteSource. They may be worth a try before you go into custom or 3rd party controls.

文本框控件中有内置功能 - AutoCompleteMode和AutoCompleteSource。在进入自定义或第三方控件之前,它们可能值得一试。

#1


9  

You will need to use some P/Inovke interop code to do this. Look for the Win32 API SendMessage function and the EM_SETCUEBANNER message.

您需要使用一些P / Inovke互操作代码来执行此操作。查找Win32 API SendMessage函数和EM_SETCUEBANNER消息。

#2


4  

Its better to post the code instead of link. I am posting this from here

最好发布代码而不是链接。我是从这里发布的

            //Copyright (c) 2008 Jason Kemp

            //Permission is hereby granted, free of charge, to any person obtaining a copy
            //of this software and associated documentation files (the "Software"), to deal
            //in the Software without restriction, including without limitation the rights
            //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
            //copies of the Software, and to permit persons to whom the Software is
            //furnished to do so, subject to the following conditions:

            //The above copyright notice and this permission notice shall be included in
            //all copies or substantial portions of the Software.

            //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
            //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
            //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
            //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
            //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
            //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
            //THE SOFTWARE.

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


            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;

                public static void SetCueText(Control control, string text)
                {
                    if (control is ComboBox)
                    {
                        COMBOBOXINFO info = GetComboBoxInfo(control);
                        SendMessage(info.hwndItem, EM_SETCUEBANNER, 0, text);
                    }
                    else
                    {
                        SendMessage(control.Handle, EM_SETCUEBANNER, 0, 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, 0, builder);
                    }
                    else
                    {
                        SendMessage(control.Handle, EM_GETCUEBANNER, 0, builder);
                    }
                    return builder.ToString();
                }
            }

#3


2  

I think the way this is generally done is to set the color of the text to gray and prefill it with your hint text.

我认为通常这样做的方法是将文本的颜色设置为灰色,并使用提示文本预填充它。

Then, write handlers for the text field's focus events, modifying the fields contents and color based when focus is gained and lost. Here's some pseudocode (sorry, it's totally not C# code. I have Actionscript on the brain right now):

然后,为文本字段的焦点事件编写处理程序,根据获得和丢失焦点时修改字段内容和颜色。这是一些伪代码(对不起,它完全不是C#代码。我现在脑部有Actionscript):

TextInput myInput;
boolean showingHint = true;

myInput.text = "Search Terms";
myInput.color = 0xcccccc;

myInput.onFocusGained = function() {
  if(showingHint) {
    myInput.text = "";
    myInput.color = 0x000000;
    showingHint = false;
  }
}

myInput.onFocusLost = function() {
  if(!showingHint && myInput.text.length == 0) {
    myInput.text = "Search Terms";
    myInput.color = 0xcccccc;
    showingHint = true;
  }
}

Remember, you only want to change the text on focus lost if the user hasn't manually changed the text. Use a separate boolean to track if you're showing the hint or not so you can differentiate between the user manually typing your "hint" text as actual content. Similarly, you only want to clear the contents of the input box if the hint is being displayed so you don't get rid of user input accidentally.

请记住,如果用户没有手动更改文本,您只想更改焦点丢失的文本。使用单独的布尔值来跟踪您是否显示提示,以便您可以区分用户手动键入“提示”文本作为实际内容。同样,如果正在显示提示,您只想清除输入框的内容,这样就不会意外地删除用户输入。

#4


1  

Give the code from this link a try. It extends the winforms functionality, as it isn't possible to achieve right out of the box. The source code is available as well. Keep in mind, it only works on Win XP or higher.

尝试从此链接中提供代码。它扩展了winforms功能,因为它无法实现开箱即用。源代码也可用。请记住,它仅适用于Win XP或更高版本。

http://www.aaronlerch.com/blog/2007/12/01/watermarked-edit-controls/

#5


0  

There is built-in functionality in the text box control -- AutoCompleteMode and AutoCompleteSource. They may be worth a try before you go into custom or 3rd party controls.

文本框控件中有内置功能 - AutoCompleteMode和AutoCompleteSource。在进入自定义或第三方控件之前,它们可能值得一试。