你能帮我解决我的问题吗?我想阻止我的文本框的粘贴并控制所有字符都是数字(WinRT)。
4 回答
从 Windows 8.1 开始,您将获得一个可以订阅的“粘贴”事件。只需订阅它并将事件的Handled
属性设置为true
以阻止它到达 TextBox。
UPDATE 1
If you want to prevent ctrl + c & ctrl + v combination, then you have to check that combination in KeyDown
event. If you get that combination you can clear the clipboard with static method Windows.ApplicationModel.DataTransfer.Clipboard.Clear();
If you don't watch for combination of keys rather then just ctrl, then also you can prevent the copy pasting via keyboards.
private void TextBox_KeyDown_1(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Control)
Windows.ApplicationModel.DataTransfer.Clipboard.Clear();
}
To allow user to enter only numeric data you can use TextBox
's TextChanged
event. Use numeric only regular expression to filter out the characters. Moreover to disable context menu of TextBox
, ContextMenuOpening
event will help you. Below is the whole code.
XAML
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<TextBox Height="50" Width="300" TextChanged="TextBox_TextChanged_1" ContextMenuOpening="TextBox_ContextMenuOpening_1" />
</Grid>
C#
private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
var tb = (TextBox)sender;
var IsNumeric = new System.Text.RegularExpressions.Regex("^[0-9]*$");
var text = tb.Text;
if (!IsNumeric.IsMatch(text))
{
int CursorIndex = tb.SelectionStart - 1;
tb.Text = tb.Text.Remove(CursorIndex, 1);
tb.SelectionStart = CursorIndex;
tb.SelectionLength = 0;
}
}
private void TextBox_ContextMenuOpening_1(object sender, ContextMenuEventArgs e)
{
e.Handled = true;
}
阻止粘贴: 1. 阻止粘贴事件
txtBox1.Paste += ADDTextBox_Paste;
void ADDTextBox_Paste(object sender, TextControlPasteEventArgs e)
{e.Handled = true;return; }
阻止 shift + insert 和 Ctrl + V 的 Keydown 事件。
void txtBox1_KeyDown(object sender, KeyRoutedEventArgs e) { var shiftState = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Shift); var ctrlState = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Control); if (((shiftState & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down && e.Key == VirtualKey.Insert) ||((ctrlState & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down && e.Key == VirtualKey.V)) { e.Handled = true; return; } }
要仅允许数字字符,您必须在 Keydown 事件中添加此代码:
if ((e.Key < VirtualKey.Number0 || e.Key > VirtualKey.Number9) &&
(e.Key < VirtualKey.NumberPad0 || e.Key > VirtualKey.NumberPad9))
{ e.handled = true; return; }
使用 Shift A 阻止整个通道。向上或向下移动箭头以阻止小零件。右键单击阻塞的通道以“复制”并粘贴。