简体   繁体   English

如何在C#Winforms程序的文本框中突出显示文本?

[英]How do I highlight Text in a Textbox in a C# Winforms program?

I have a C# Winforms program with multiple textboxes. 我有一个带有多个文本框的C#Winforms程序。 I used the properties for each box to place text in them, explaining to the user what value goes in them. 我使用每个框的属性在其中放置文本,向用户解释其中的值。 I want the text to highlight whenever a user selects that box. 每当用户选择该框时,我希望文本突出显示。 By either tabbing or mouse click. 通过Tab键或鼠标单击。 I won't have to do this if there's a way to display what value goes in the textbox somewhere outside of it. 如果有一种方法可以显示文本框中除了它之外的某个值,我就不必这样做了。

I tried the Textbox.select method but it had no effect. 我尝试了Textbox.select方法,但没有效果。 The same with this . 相同。

Here's a Screenshot of my program. 这是我的程序的屏幕截图

My Code: 我的代码:

    private void grapplingText1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
    {
        grapplingText1.SelectionStart = 0;
        grapplingText1.SelectionLength = grapplingText1.Text.Length;

Will this do, or is more required? 这样做,还是更需要?

How about you assign ToolTip to TextBox and put all the "talk what textbox is for" inside that? 你怎么样将ToolTip分配给TextBox并将所有“对话是什么文本框”放在那里?

Just drag & drop ToolTip inside the Form. 只需在Form中拖放ToolTip And then in each TextBox properties you should have additional entry in Misc section ToolTip on toolTip1 (or whatever it's name will be if you rename it). 然后在每个TextBox属性中,你应该在toolTip1上的Misc部分ToolTip有额外的条目(或者如果你重命名它的名字将是什么)。

Then when user hovers over TextBox (Read Only/Disabled TextBox doesn't seems to display ToolTips) and stops there for 1 second ToolTip should show with proper info. 然后,当用户将鼠标悬停在TextBox (Read Only / Disabled TextBox似乎不显示工具提示)并在那里停留1秒钟,ToolTip应显示正确的信息。

You can eventually or even better have a Label next to TextBox saying what is is, but having a ToolTip is also a good idea to explain more information to user thru that. 你最终甚至可以更好地在TextBox旁边有一个Label说明是什么,但是使用ToolTip也是一个好主意,通过它向用户解释更多信息。

For doing stuff with WaterMark so you don't have to go the long way by setting the events, taking care of SelectAll etc you could do it like this. 对于使用WaterMark做的事情,所以你不必通过设置事件,照顾SelectAll等来做很长的事情,你可以这样做。 Create new watermark.cs file and replace it with this code. 创建新的watermark.cs文件并将其替换为此代码。 Make sure you have changed namespace to match your program namespace. 确保已更改名称空间以匹配程序命名空间。

#region
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

#endregion

namespace Watermark {
    public static class TextBoxWatermarkExtensionMethod {
        private const uint ECM_FIRST = 0x1500;
        private const uint EM_SETCUEBANNER = ECM_FIRST + 1;
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
        public static void SetWatermark(this TextBox textBox, string watermarkText) {
            SendMessage(textBox.Handle, EM_SETCUEBANNER, 0, watermarkText);
        }
    }
}
   internal class WatermarkTextBox : TextBox {
    private const uint ECM_FIRST = 0x1500;
    private const uint EM_SETCUEBANNER = ECM_FIRST + 1;
    private string watermarkText;
    public string WatermarkText {
        get { return watermarkText; }
        set {
            watermarkText = value;
            SetWatermark(watermarkText);
        }
    }
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
    private void SetWatermark(string watermarkText) {
        SendMessage(Handle, EM_SETCUEBANNER, 0, watermarkText);
    }
}

In your Form you activate it like this: 在您的表单中,您可以像这样激活它:

textBoxYourWhatever.SetWatermark("Text that should display");

It stays there as long the TextBox is empty. 只要TextBox为空,它就会一直存在。 When users gets into TextBox text disappears. 当用户进入TextBox文本消失时。 It appears again when TextBox is cleaned (either by user or automatically). 当清除TextBox (由用户或自动)时,它会再次出现。 No need for any special events etc. 不需要任何特殊活动等

EDIT: 编辑:

I've added also internal class WaterMarkTextBox which gives you an option to simply use new WaterMarkTexBox that becomes available in Designer. 我还添加了内部类WaterMarkTextBox,它为您提供了一个选项,可以简单地使用Designer中可用的新WaterMarkTexBox。 Then drag and drop it to your designer and use it. 然后将其拖放到您的设计器并使用它。 It behaves like normal textbox just gives you additional field WaterMarkText. 它的行为与普通文本框一样,只为您提供了额外的字段WaterMarkText。

I still prefer the first method thou. 我还是喜欢第一种方法。 Doesn't make you rebuild your gui again. 不会让你再次重建你的gui。

I think .select will work if you know the text amount you want to select. 我认为如果您知道要选择的文本数量,.select将起作用。

Try .SelectAll(); 试试.SelectAll(); It should work for you 它应该适合你

You need to use the TextBox.Focus() to get the focus on your control, and if doesn't automatically work, then just call the SelectAll() method on the Enter() event. 您需要使用TextBox.Focus()来关注控件,如果不能自动工作,则只需在Enter()事件上调用SelectAll()方法。

private TextBox1_Enter(object sender, EventArgs e) {    
    TextBoxTextHighlight(sender, null);
}

private TextBox2_Enter(object sender, EventArgs e) {
    TextBoxTextHighlight(sender, null);
}

private TextBox3_Enter(object sender, EventArgs e) {
    TextBoxTextHighlight(sender, null);
}

// And so forth...

private void TextBoxTextHighlight(object sender, EventArgs e) {
    (sender as TextBox).SelectAll();
}

This method will allow you to call it from any TextBoxX_Enter() event handler. 此方法允许您从任何TextBoxX_Enter()事件处理程序中调用它。

Otherwise, you even could create a new UserControl, call it whatever you want upon creation, then, when created into your project, edit the code and replace the inheritence of UserControl class by the TextBox class, then define within it the default behaviour you would like to have on the Enter() event, like this call to the SelectAll() method, and make it protected virtual, and within the constructor, you may subscribe the event handler like so: 否则,您甚至可以创建一个新的UserControl,在创建时调用它,然后,当创建到项目中时,编辑代码并用TextBox类替换UserControl类的继承,然后在其中定义默认行为喜欢在Enter()事件上,比如调用SelectAll()方法,并使其成为受保护的虚拟,并且在构造函数中,您可以像这样订阅事件处理程序:

public partial class CustomTextBox : TextBox {
    public CustomTextBox() 
        : base() {
        this.Enter += new EventHandler(Enter);
    }

    protected virtual Enter(object sender, EventArgs e) {
        this.SelectAll();
    }
}

I wrote it on the fly, so perhaps a few modifications are required, but you may get the idea. 我是在飞行中写的,所以也许需要进行一些修改,但你可能会得到这个想法。 But I do not advise you to do so unless it's really worthy doing it for your proper situation. 但我不建议你这样做,除非它真的值得为你的正常情况做这件事。 The simpler the better, and the simplest is to create an event handler for each of your form's TextBoxes and then call the TextBoxTextHighlight() method. 越简单越好,最简单的方法是为每个表单的TextBox创建一个事件处理程序,然后调用TextBoxTextHighlight()方法。

Suppose that your textbox´s name is 'MyTextBox' 假设您的文本框名称为“MyTextBox”

You can write the method to handle the Focus event: 您可以编写处理Focus事件的方法:

private void MyTextBox_GotFocus(object sender, EventArgs e)
{
    MyTextBox.SelectionStart = 0;
    MyTextBox.SelectionLength = MyTextBox.Text.Length;
    MyTextBox.Select();
}

You´ll need to add the event handler too: 您还需要添加事件处理程序:

this.MyTextBox.GotFocus += new System.EventHandler(this.MyTextBox_GotFocus);

This should work... 这应该工作......

EDIT 编辑

You can use the same method for other textbox, just add the event handler: 您可以对其他文本框使用相同的方法,只需添加事件处理程序:

this.MyTextBox2.GotFocus += new System.EventHandler(this.MyTextBox_GotFocus);
this.MyTextBox3.GotFocus += new System.EventHandler(this.MyTextBox_GotFocus);
this.MyTextBox4.GotFocus += new System.EventHandler(this.MyTextBox_GotFocus);
//...

Typically, if you want to explain to the user what goes in a textbox, you place a Label control directly above it, (or to the side). 通常情况下,如果你想解释发生的事情一个文本框的用户,您将一个标签控件直接上面,(或侧面)。

Sometimes though, to save screen real-estate, you can put a description of the text inside of the textbox itself. 有时候,为了节省屏幕空间,您可以在文本框本身内部放置文本说明。 This is called a watermark . 这被称为水印

The simplest way to show some additional information when hovering over an item would be to use a Tooltip. 将鼠标悬停在某个项目上时显示其他信息的最简单方法是使用工具提示。 I've tried a similar watermark approach but having found there's no immediate way to implement it the Tooltip seemed to be a suitable alternative. 我尝试了类似的水印方法,但发现没有直接的方法来实现它,Tooltip似乎是一个合适的选择。

You can see how to implement it at the following link: Implementing a tooltip 您可以在以下链接中查看如何实现它: 实现工具提示

I have found that in my application, attaching the highlight method to the Focus -> Enter event did not work well with the SelectAll() method. 我发现在我的应用程序中,将高亮显示方法附加到Focus - > Enter事件并不适用于SelectAll()方法。 I instead used Action -> Click (which I believe only works for mice) and attached my highlighting method there. 我改为使用Action - > Click(我相信它只适用于鼠标)并在那里附加我的突出显示方法。 Now it works like a charm. 现在它就像一个魅力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM