我正在制作一个数字猜谜游戏,为方便起见,我想在我的程序中添加一行代码,只需点击一下即可选择文本框中的所有文本。我已经尝试了我在这里找到的所有内容,以及我在谷歌上发现的其他故障排除网站,似乎没有任何工作,甚至试图强调关注文本框。文本框的行为仍然像普通文本框一样,即必须双击才能选择所有文本框。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace randomNumberGuessingGameFourthTry
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void startGame_Click(object sender, EventArgs e)
{
if (min.Text == "" || min.Text == " " || min.Text == "Min")
{
MessageBox.Show("You didn't enter a minimum value of zero or greater so the default value of 0 was set.");
min.Text = "0";
}
if (max.Text == "" || max.Text == " " || max.Text == "Max")
{
MessageBox.Show("You didn't enter a maximum value so the default value of 10 was set.");
max.Text = "11";
}
startGuessing startGame = new startGuessing(min.Text, max.Text);
this.Hide();
startGame.ShowDialog();
}
private void exitGame_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void min_TextChanged(object sender, EventArgs e)
{
min.Focus();
min.SelectAll();
min.SelectionLength = min.Text.Length;
int userInput1 = Convert.ToInt32(min.Text);
if (!(userInput1 >= 0))
{
MessageBox.Show("Your min range must be at least 0 or higher", "Invalid range found");
}
}
private void max_TextChanged(object sender, EventArgs e)
{
int userInput1 = Convert.ToInt32(min.Text);
int userInput2 = Convert.ToInt32(max.Text);
if (!(userInput2 <= userInput1 + 9))
{
MessageBox.Show("Your max range must be at least 10 digits higher than " + userInput1, "Invalid range found");
}
}
}
}
以上是我的form1.cs的代码我想如果我能在这里工作,我可以让它在我的第二个表单上工作。
答案 0 :(得分:2)
您应首先调用SelectAll()
方法,然后调用Focus()
,反之亦然。这个最小的例子对我有用:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.Click += TextBoxOnClick;
}
private void TextBoxOnClick(object sender, EventArgs eventArgs)
{
var textBox = (TextBox) sender;
textBox.SelectAll();
textBox.Focus();
}
}
答案 1 :(得分:0)
你尝试了什么?
以下对我来说很好:
private void textBox1_Click(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
textBox.SelectAll();
}
当然,您需要将textBox1_Click()
添加为TextBox
的{{1}}事件的事件处理程序。
请注意,上述操作将导致在控件中单击鼠标即可完全选择始终的文本。这将使得无法使用鼠标选择文本的部分。如果您想要更复杂的行为,可以使用此处的答案:
Making a WinForms TextBox behave like your browser's address bar