在粘贴到文本框C#(Ctrl + V和右键单击 - >粘贴)之前,是否有一些方法可以在剪贴板中仅检查剪贴板中的字符数,而不使用MarkedTextbox。
答案 0 :(得分:2)
在文本框文本中添加规则更改为仅接受数字:
private string value;
private void textBox1_TextChanged(object sender, EventArgs e)
{
// at this moment value is still old
var oldValue = value;
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
MessageBox.Show("Please enter numbers only.");
textBox1.Text = oldvalue;
}
else{
value = ((TextBox)sender).Text;
}
}
答案 1 :(得分:0)
我怀疑在粘贴到TextBox之前有任何检查,我建议订阅KeyDown
和MouseClick
事件,并编写自己的逻辑。
protected override void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
// Your logic to read clipboard content and check length.;
}
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
// You logic goes here.
}
}
您可以从MSDN获取有关如何读/写剪贴板内容的帮助。
答案 2 :(得分:0)
我想〜你想要一个只能接受数字的TextBox吗?
如果是,则通过SetWindowLong()在TextBox上设置ES_NUMBER样式:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form2_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
SetNumbersOnlyTextBox(this.textBox1);
}
public const int GWL_STYLE = (-16);
public const int ES_NUMBER = 0x2000;
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
public void SetNumbersOnlyTextBox(TextBox TB)
{
SetWindowLong(TB.Handle, GWL_STYLE, GetWindowLong(TB.Handle, GWL_STYLE) | ES_NUMBER);
}
}
或者,您可以从TextBox继承并在CreateParams()中设置ES_NUMBER:
public class IntegerTextBox : TextBox
{
private const int ES_NUMBER = 0x2000;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style = cp.Style | ES_NUMBER;
return cp;
}
}
}
答案 3 :(得分:0)
如果你真的只想允许只有数字的贴片,那么从TextBox继承并捕获WM_PASTE,在需要时禁止显示消息:
public class DigitsOnlyOnPasteTextBox : TextBox
{
private const int WM_PASTE = 0x302;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_PASTE && Clipboard.ContainsText())
{
int i;
string txt = Clipboard.GetText();
foreach(char c in txt)
{
if (!char.IsNumber(c))
{
return;// suppress default behavior
}
}
}
base.WndProc(ref m); // allow normal processing of the message
}
}