After spending 90 minutes searching for a solution to this simple problem I have to post a question in shame.
I'm working on a WPF project where the user inputs text. I want to check the inputs while the user is typing, display a tool tip and ideally block characters that are not allowed. Basically it's this thread:
How do I validate characters a user types into a WinForms textbox? or this
Is there a best practice way to validate user input?
private void NameTextbox_KeyDown(object sender, KeyEventArgs e)
{
e.???
}
I created this code behind by double clicking in the KeyDown-Property Field in the designer (just mentioning this if I messed up there).
Screenshot of the Property Window
I can not access the e.SupressKeyPress Property. Why?
As of the Properties offered by VS I think that e is of the wrong Type or in the wrong context here.
Intellisense Screenshot
Edit1
private void NameTextbox_KeyDown(object sender, KeyEventArgs e)
{
var strKey = new KeyConverter().ConvertToString(e.Key);
if (!strKey.All(Char.IsLetter))
{
MessageBox.Show("Wrong input");
e.Handled = true;
}
}
Thanks to #rokkerboci I was able to build something that kind of works.
Yet I think it is overly complex. So improvements are still welcome :)
New Error When Creating a Message Box the application hangs without an exception thrown.
You are using WPF, which does not include the WindowsForms specific SupressKeyPress property.
You can do this in WPF by using the KeyDown event, and setting the KeyEventArgs.Handled property to true (it tells the handler, that it doesn't have to do anything with this event.)
private void NameTextbox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
MessageBox.Show("delete pressed");
e.Handled = true;
}
}
EDIT:
I have found a perfect answer to your question:
C#:
char[] invalid = new char[] { 'a', 'b' };
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
foreach (var item in invalid)
{
if (e.Text.Contains(item))
{
e.Handled = true;
return;
}
}
}
private void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
{
var text = e.DataObject.GetData(typeof(string)).ToString();
foreach (var item in invalid)
{
if (text.Contains(item))
{
e.CancelCommand();
return;
}
}
}
XAML:
<TextBox PreviewTextInput="TextBox_PreviewTextInput" DataObject.Pasting="TextBox_Pasting" />
Related
I am trying to make an app that scan barcodes from a usb scanner. The app is supposed to look for jobs corresponding the code from the barcode. My current problem is that when I try the app, it only takes 1 character and tries to look for the job corresponding that said character instead of allowing me to type an entire string and press enter.
Here is my code:
public void SearchJob(object sender, EventArgs e)
{
this.ChangeCurrentEntity(this.Manager.GetEntity(j => j.Code == this.TypedView.BarcodeNumber)?.FirstOrDefault());
this.LoadView();
if (this.confirmation.GetConfirmation())
{
var tokenSource = new CancellationTokenSource();
this.task = Task.Run(() => { }, tokenSource.Token);
if (!task.IsCompleted)
tokenSource.Cancel();
if (dcConfig.CancelCode == "CancelCode")
{
this.Host.CloseHost();
}
}
this.TypedView.BarcodeNumber = "";
}
getConfirmation() is a popUp to confirm the job, which is currently not relevant to my problem I think.
This is from my form:
private void JobNumberTextBox_TextChanged(object sender, EventArgs e)
{
JobEntered?.Invoke(this, e);
}
Any help would be greatly appreciated.
You are waiting on the wrong event. You need to wait on the KeyPress event
private void JobNumberTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == (char)Keys.Return)
{
e.Handled = true;
JobEntered?.Invoke(this, e);
}
}
Side note: most barcode scanners can be configured to add an Enter key after a scan
I think I solved my issue.
I removed my text changed function and replaced it with a Keydown function so that when I press enter the event to search for a job triggers(that way i am allowed to type a full string in). I also binded my Keydown with my TextBox.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
JobEntered?.Invoke(this, e);
}
}
I am making a game where I need a constant keyboard listener (to navigate through the game). I tried getting the keyboard focus to one place and let it stay there using a seperate thread in a while true loop. This seems to crash my program.
Question:
Is there a method to get my keyboard focused on one element so I can grab my key input from there?
What can I use?:
something that works without throwing exceptions
something I can use in combination with other text input
something that doesn't take hours to compile
something that is easy to build another program (im not super good at c#)
What have I tried?
public MainWindow()
{
InitializeComponent();
Thread keyboardfocus = new Thread(GetFocus);
keyboardfocus.Start();
}
private void GetFocus()
{
while (true)
{
Keyboard.Focus(KeyboardButton);
}
}
private void KeyboardButton_OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Z)
{
map.PosUp -= 1;
MainCanvas.Background = Brushes.Aqua;
}
else if (e.Key == Key.S)
{
map.PosUp += 1;
MainCanvas.Background = Brushes.Black;
}
}
Thanks
Add event handler for Window.Loaded and set there a focus to the desired control:
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Keyboard.Focus(KeyboardButton);
}
Add event handler for the UIElement.LostKeyboardFocus in your case KeyboardButton and just set the keybord focus again to the KeyboardButton:
private void KeyboardButton_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
Keyboard.Focus(KeyboardButton);
}
I have the following code:
private void myTextBox_Validating(object sender, CancelEventArgs e)
{
if (some condition)
{
e.Cancel = true;
errorProvider.SetError(myTextBox, "Error occurred");
return;
}
this.errorProvider.SetError(this.myTextBox, null);
}
And the following Button_click code to trigger all Validating events:
private void saveData_Click(object sender, EventArgs e)
{
if (!this.ValidateChildren())
{
return;
}
}
It did validate correctly. However, I can't seem to click anywhere besides myTextBox when I click that texbox without changing its invalid value. Can I disable that "locking to your error until you change it" feature?
You can control the behaviour of your controls, whether they are allowed to lose focus while having invalid data or not.
On your form you can set the following property:
this.AutoValidate = AutoValidate.EnableAllowFocusChange;
For details and other ways of getting a similar effect, please have a look at the docs
I want to create a login page based C# desktop application. I use the bunifu toolbox to create a login page design. But when I want to create a password field using the bunifumaterialtextbox, the textbox does not show any changes / it only displays alphabet. It looks like the ispassword contained in the textbox properties is not working. So what should I do so that this texbox can display the correct password (not displaying alphabeth) when the program is run ?. I apologize for any errors in this question.
is just a easy solution i have found
private void passbox_OnValueChanged(object sender, EventArgs e)
{
passbox.isPassword = true;
}
I'm new using the Bunifu framework tool and I had the same problem then you. The solution I found was to invoke the _TextBox method which I suppose that gives you all the normal TextBox controls.
My code was something like this:
txtPassword._TextBox.PasswordChar = '*';
I loaded this code inside the Form_Load code block. It worked for me, hope that be useful for you too. Good luck!
in side the properties tab of the bunifu text box there is a property ispassword set it to true.
to fully make the bunifu textbox to passwordbox you have to do the following:
1.in side the properties tab of the bunifu text box there is a property ispassword set it to False.
2.create an event of Enter and use the following code:
3.create an event of Leave and use the following code:
private void txtpassword_Enter(object sender, EventArgs e)
{
if (txtpassword.Text == "Password")
{
txtpassword.Text = "";
txtpassword.isPassword = true;
}
}
private void txtpassword_Leave(object sender, EventArgs e)
{
if (txtpassword.Text == "")
{
txtpassword.Text = "Password";
txtpassword.isPassword = false;
}
}
like this
You can use the UseSystemPasswordChar property in your text box.
Example:
TextBox1.UseSystemPasswordChar = true;
this problem's solution is using enter,leave and textchange event such as below code if the name of your text box is txtPassword:
private void txtPassword_TextChange(object sender, System.EventArgs e)
{
if (txtPassword.Text.Trim() != "")
{
txtPassword.PasswordChar = '*';
}
else
{
txtPassword.PasswordChar = '\0';
}
}
private void txtPassword_Leave(object sender, System.EventArgs e)
{
if (txtPassword.Text.Trim() == "")
{
txtPassword.PasswordChar = '\0';
txtPassword.TextPlaceholder = "insert your placeholder..";
}
}
private void txtPassword_Enter(object sender, System.EventArgs e)
{
if (txtUserName.Text.Trim() != "")
{
txtPassword.PasswordChar = '*';
txtPassword.PlaceholderText = "";
}
}
Most of my dropdown boxes use the SuggestAppend property, meaning when you start typing in the box, it will make a shortlist of the items that match your case. However, if I do this after opening the drawer, this happens:
I have tried using this method, but it closes both instead of just one:
private void cmbLoc_TextChanged(object sender, EventArgs e)
{
if (cmbLoc.Text != "")
{
cmbLoc.DroppedDown = false;
}
}
I am trying to have it so that when I type something into the text box, the original dropdown will disappear, and the SuggestAppend draw will appear. How can I manage this?
It worked if I used KeyDown. Try and tell if that helps
private void cmbLoc_KeyDown(object sender, KeyEventArgs e)
{
var comboBox = (ComboBox)sender;
comboBox.DroppedDown = false;
}