是否有一种简单的方法来缩进多行选择,方法是按Tab键或shift-tab删除C#文本框控件(VS2008)中每个选定行开头的标签?
答案 0 :(得分:0)
您可以将TextBox'AcceptsTab属性设置为true
。这将允许您在控件中输入制表符。
但是,不支持使用Shift + Tab删除缩进。您可能必须处理KeyPress事件并自行删除插入符号下的制表符。
编辑:我误解了这个问题。要实现类似Visual Studio的缩进/ dedent功能,请尝试类似:
private bool _shiftTabKeyDown;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
_shiftTabKeyDown = false;
if (e.KeyCode == Keys.Tab && e.Shift) {
_shiftTabKeyDown = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox1.SelectionLength == 0 || e.KeyChar != '\t') {
return;
}
bool startNewLineAdded = false;
bool endNewLineRemoved = false;
string selection = textBox1.SelectedText;
if (!selection.StartsWith(Environment.NewLine)) {
selection = Environment.NewLine + selection;
startNewLineAdded = true;
}
if (selection.EndsWith(Environment.NewLine)) {
selection = selection.SubString(0, selection.Length
- Environment.NewLine.Length);
endNewLineRemoved = true;
}
if (_shiftTabKeyDown) {
selection = selection.Replace(Environment.NewLine + '\t',
Environment.NewLine);
} else {
selection = selection.Replace(Environment.NewLine,
Environment.NewLine + '\t');
}
if (startNewLineAdded) {
selection = selection.SubString(Environment.NewLine.Length);
}
if (endNewLineRemoved) {
selection += Environment.NewLine;
}
textBox1.SelectedText = selection;
e.Handled = true;
}
答案 1 :(得分:0)
也许这实际上很复杂,我不知道。但是以下解决方案为您提供了一个想法,基本上可行。你必须自己实现删除,我没有真正测试代码。这只是为了让您了解如何做到这一点。
class Class1 : TextBox
{
protected override bool IsInputKey(Keys keyData)
{
switch (keyData & Keys.KeyCode)
{
case Keys.Tab:
return true;
}
return base.IsInputKey(keyData);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == '\t' && SelectedText.Contains(Environment.NewLine))
{
string start = string.Empty;
if(SelectionStart > 0)
start = Text.Substring(0, SelectionStart);
string exchange = Text.Substring(SelectionStart, SelectionLength);
string end = string.Empty;
if(SelectionStart + SelectionLength < Text.Length - 1)
end = Text.Substring(SelectionStart + SelectionLength);
Text = start + '\t' +
exchange.Replace(Environment.NewLine, Environment.NewLine + "\t") +
end;
e.Handled = true;
}
base.OnKeyPress(e);
}
}
答案 2 :(得分:0)
以下代码段使用了我编写的两个(普通)扩展方法(SelectFullLines
,ReplaceRegex
),但方法应该是明确的:
private void txtScript_KeyDown(object sender, KeyEventArgs e)
{
txtScript.SelectFullLines();
if (!e.Shift) {
txtScript.SelectedText = txtScript.SelectedText.ReplaceRegex("^", "\t", System.Text.RegularExpressions.RegexOptions.Multiline);
} else {
txtScript.SelectedText = txtScript.SelectedText.ReplaceRegex("^\\t", "", System.Text.RegularExpressions.RegexOptions.Multiline);
}
}
您还需要设置txtScript.AcceptsTab = True
。