![](/img/trans.png)
[英]c#: showing the selection of text in a textbox while another form is focused
[英]Remove the Selection of text in textBox in C#
我有一個文本框,我必須允許用戶在該文本框中鍵入某些內容,並且還限制用戶不要在該文本框中選擇鍵入的文本。我不必在開始時留白文本框,我也不必允許用戶鍵入超過32個字符。這是我的代碼。
private void txtApplication_Title_KeyPress(object sender, KeyPressEventArgs e)
{
txtApplication_Title.Text = txtApplication_Title.Text.Remove(txtApplication_Title.SelectionStart, txtApplication_Title.SelectionLength);
if (txtApplication_Title.Text.Length== 0)
{
e.Handled = (e.KeyChar == (char)Keys.Space);
}
int count_charac = txtApplication_Title.Text.Length + 1 ;
if (count_charac > 32)
{
lblApplication_name.Text = data_variables.RES_TXT_STRING_EXCEEDING_APPLICATION_NAME;
timer1.Interval = 7000;
timer1.Enabled = true;
timer1.Tick += new System.EventHandler(OnTimerEvent_Application_name);
}
}
public void OnTimerEvent_Application_name(object sender, EventArgs e)
{
lblApplication_name.Text = " ";
timer1.Dispose();
}
在此代碼中,我能夠將用戶限制為32個字符。並且我嘗試在開始時按空格鍵,但不允許我這樣做。它允許使用Shift +箭頭鍵選擇文本。 我確實知道如何阻止選擇。另一件事是假設我嘗試打招呼,然后選擇地獄並直接按空格,開始在文本框中允許空格。任何人都可以幫幫我。謝謝
如果要阻止用戶選擇文本,請執行以下操作:
Label
代替TextBox
。 可以使用textchanged事件代替KeyPress事件。
文本框具有最大長度屬性。 另外,只需調用TextBox.Text = TextBox.Text.TrimStart()即可在開始時刪除所有空格
您將要觀看TextChanged事件-每當文本框的內容發生更改時, 它就會讓您知道。 您可以使用user623879建議的TrimStart()方法,而不是檢查長度是否為0。
當您說刪除選擇時,您是說刪除用戶選擇的文本嗎? 如果只想使選擇“離開”,則可以將SelectionLength屬性設置為0。
您需要在文本框KeyPress,MouseUp和MouseMove事件上將SelectionLength設置為0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.