我有很多文本框。我有一个按钮,可以剪切聚焦文本框的选定文本。我怎么做?我试过这个:
if (((TextBox)(pictureBox1.Controls[0])).SelectionLength > 0)
{
((TextBox)(pictureBox1.Controls[0])).Cut();
}
答案 0 :(得分:6)
希望它是WinForms
var textboxes = (from textbox in this.Controls.OfType<TextBox>()
where textbox.SelectedText != string.Empty
select textbox).FirstOrDefault();
if (textboxes != null)
{
textboxes.Cut();
}
答案 1 :(得分:4)
循环浏览控件以找到具有所选文本的控件:
foreach (Control x in this.PictureBox1.Controls)
{
if (x is TextBox)
{
if (((TextBox)x).SelectionLength > 0)
{
((TextBox)(x).Cut(); // Or some other method to get the text.
}
}
}
希望这有帮助!
答案 2 :(得分:1)
尝试使用常见的Enter
和Leave
事件来设置最后一个拥有Focus的TextBox。
private void textBox_Enter(object sender, EventArgs e)
{
focusedTextBox = null;
}
private void textBox_Leave(object sender, EventArgs e)
{
focusedTextBox = (TextBox)sender;
}
private void button1_Click(object sender, EventArgs e)
{
if (!(focusedTextBox == null))
{
if (focusedTextBox.SelectionLength > 0)
{
Clipboard.SetText(focusedTextBox.SelectedText);
focusedTextBox.SelectedText = "";
focusedTextBox = null;
}
}
}