C# 自动清除 Winform 文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-01 08:52:13  来源:igfitidea点击:

C# Auto Clearing Winform Textbox

提问by Robin Robinson

I have a user that want to be able to select a textbox and have the current text selected so that he doesn't have to highlight it all in order to change the contents.

我有一个用户希望能够选择一个文本框并选择当前文本,这样他就不必为了更改内容而将其全部突出显示。

The contents need to be handle when enter is pushed. That part I think I have figured out but any suggestions would be welcome.

按下回车时需要处理内容。那部分我想我已经想通了,但欢迎提出任何建议。

The part I need help with is that once enter has been pushed, any entry into the textbox should clear the contents again.

我需要帮助的部分是,一旦按下输入,文本框中的任何条目都应再次清除内容。

Edit:The textbox controls an piece of RF hardware. What the user wants to be able to do is enter a setting and press enter. The setting is sent to the hardware. Without doing anything else the user wants to be able to type in a new setting and press enter again.

编辑:文本框控制一块 RF 硬件。用户希望能够做的是输入设置并按回车键。设置被发送到硬件。无需做任何其他操作,用户希望能够输入新设置并再次按 Enter。

采纳答案by Greg Hurlman

Hook into the KeyPress event on the TextBox, and when it encounters the Enter key, run your hardware setting code, and then highlight the full text of the textbox again (see below) - Windows will take care of clearing the text with the next keystroke for you.

钩入 TextBox 上的 KeyPress 事件,当它遇到 Enter 键时,运行你的硬件设置代码,然后再次突出显示文本框的全文(见下文)——Windows 将负责在下一次击键时清除文本为你。

TextBox1.Select(0, TextBox1.Text.Length);

回答by Rob Cooper

OK, are you sure that is wise? I am picturing two scenarios here:

好的,你确定这是明智的吗?我在这里描绘了两个场景:

  1. There is a default button on the form, which is "clicked" when enter is pushed".
  2. There is no default button, and you want the user to have to press enter, regardless.
  1. 表单上有一个默认按钮,按下回车键时“单击”。
  2. 没有默认按钮,您希望用户无论如何都必须按 Enter。

Both of these raise the same questions:

这两个都提出了同样的问题:

  • Is there any validation that is taking place on the text?
  • Why not create a user control to encapsulate this logic?
  • If you know the enter button is being pushed and consumed fine, how are you having problems with TextBoxName.Text = string.Empty?
  • 是否对文本进行了任何验证?
  • 为什么不创建一个用户控件来封装这个逻辑呢?
  • 如果您知道按下 Enter 按钮并正常使用,那么TextBoxName.Text = string.Empty 有什么问题?

Also, as a polite note, can you please try and break up your question a bit? One big block is a bit of a pain to read..

另外,作为礼貌的说明,你能试着把你的问题分解一下吗?一大块读起来有点痛苦..