2008-09-05 22 views
9

Estoy trabajando en una aplicación C# winforms (VS.NET 2008, .NET 3.5 sp 1). Tengo un campo de búsqueda en un formulario, y en lugar de tener una etiqueta al lado del campo de búsqueda, me gustaría mostrar un texto gris en el fondo del campo de búsqueda mismo ('Términos de búsqueda', por ejemplo). Cuando el usuario comienza a ingresar texto en el campo de búsqueda, el texto debería desaparecer. ¿Cómo puedo conseguir esto?Mostrando una sugerencia para un control de edición de C# winforms

Respuesta

9

Deberá usar algún código de interoperabilidad P/Inovke para hacerlo. Busque la función Win32 API SendMessage y el mensaje EM_SETCUEBANNER.

0

Hay una función incorporada en el control de cuadro de texto - AutoCompleteMode y AutoCompleteSource. Puede valer la pena intentarlo antes de entrar en controles personalizados o de terceros.

2

creo que la forma en que esto generalmente se hace es establecer el color del texto a gris y llenar previamente con su texto pista.

A continuación, escriba controladores para los eventos de foco del campo de texto, modificando el contenido de los campos y el color cuando se gana y se pierde el foco. He aquí algunos pseudocódigo (lo siento, es totalmente no es código C# He Actionscript en el cerebro en este momento.):

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; 
    } 
} 

Recuerde que sólo desea cambiar el texto enfocado perdido si el usuario no ha cambiado manualmente el texto. Use un booleano por separado para rastrear si está mostrando la sugerencia o no, para que pueda diferenciar entre el usuario que escribe manualmente su texto de "sugerencia" como contenido real. De forma similar, solo desea borrar el contenido del cuadro de entrada si se muestra la sugerencia para que no se deshaga accidentalmente de la entrada del usuario.

4

Es mejor publicar el código en lugar del enlace. Estoy posteando esto desde 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(); 
       } 
      } 
Cuestiones relacionadas