我使用Juce Library开发C++已有几个月。我在项目中编写了一个代码,其中文本框的格式被修改为仅具有一些功能的十六进制值:
演示:
12 ab 32 a5 64
现在,如果我的光标位于末尾,并且我继续按Backspace键,它将删除一般文本框中出现的值。
现在,如果我的光标位于a5的开头,并且我按了“删除键”,则该值应变为:
12 ab 32 56 4
如果我的光标位于a5的末尾,并且我按了'delete键',则什么也不会发生。在输入值时,空格键不应让bw的两个值隔开。只能输入a-f和0-9。
这里的C++代码:
void CMSP430CommPanel::textEditorTextChanged (TextEditor& editor)
{
if(&editor == m_texti2cWrite)
{
int count = 0;
int location;
String text1 = m_texti2cWrite->getText();
String text = m_texti2cWrite->getText().removeCharacters(" ");
String hexString = String::empty;
int countCaret = m_texti2cWrite->getCaretPosition();
for(int i=0; i < text.length(); i++)
{
hexString = hexString + String (&text[i], 1);
if((i+1) % 2 == 0)
{
if(i != text.length()-1)
{
hexString = hexString + T(" ");
count ++;
}
}
count ++;
}
m_texti2cWrite->setText(hexString,false);
if(text1.length() == m_texti2cWrite->getCaretPosition())
{
m_texti2cWrite->setCaretPosition(count);
}
else
{
m_texti2cWrite->setCaretPosition(countCaret);
}
}
}
我希望同一件事在我的WPF应用程序中工作。可以说C#中相同代码的一般实现。
请帮忙!!!
最佳答案
尝试以下操作(您的TextBox的TextChanged-Event):
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox m_texti2cWrite = (TextBox)sender;
int count = 0;
string text1 = m_texti2cWrite.Text;
string text = m_texti2cWrite.Text.Replace(" ", string.Empty);
string hexString = string.Empty;
int countCaret = e.Changes.ToList()[0].Offset;
for (int i = 0; i < text.Length; i++)
{
hexString += text[i];
if ((i + 1) % 2 == 0)
{
if (i != text.Length - 1)
{
hexString = hexString + " ";
count++;
}
}
count++;
}
m_texti2cWrite.Text = hexString;
if (text1.Length == countCaret)
{
m_texti2cWrite.Select(count, 0);
}
else
{
if (e.Changes.ToList()[0].RemovedLength == 0)
{
m_texti2cWrite.Select(countCaret + 1, 0);
if (string.IsNullOrWhiteSpace(hexString.Substring(countCaret, 1)))
m_texti2cWrite.Select(countCaret + 2, 0);
}
else
{
m_texti2cWrite.Select(countCaret, 0);
if (string.IsNullOrWhiteSpace(hexString.Substring(countCaret, 1)))
m_texti2cWrite.Select(countCaret + 1, 0);
}
}
}
}
编辑(仅接受数字,控制键或a-f):
private Boolean IsTextAllowed(String text)
{
string acceptedChars = "ABCDEFabcdef";
foreach (Char c in text.ToCharArray())
{
if (Char.IsDigit(c) || Char.IsControl(c) || acceptedChars.Contains(c)) continue;
else return false;
}
return true;
}
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsTextAllowed(e.Text);
}