KeyCode and keyboard layout and language - c#

I need to include the asterisk as an allowable entry on a text box.
How can I test for this key under the KeyDown event regardless of the keyboard layout and language?
Ignoring the numeric keypad, with the Portuguese QWERTY layout this key can be tested through Keys.Shift | Keys.Oemplus. But that will not be the case for other layouts or languages.

You are using the wrong event, you should be using KeyPressed. That fires when the user presses actual typing keys. KeyDown is useless here, the virtual key gets translated to a typing key according to the keyboard layout. Hard to guess what that might be unless you translate the keystroke yourself. That's hard.
Some code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
string allowed = "0123456789*\b";
if (allowed.IndexOf(e.KeyChar) < 0) e.Handled = true;
}
The \b is required to allow the user to backspace.

Use KeyPress event
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
int keyValue = e.KeyChar;
textBox1.Text = Convert.ToChar(keyValue).ToString();
}

InitializeComponent();
//SET FOCUS ON label1 AND HIDE IT
label1.Visible = false;
label1.Select();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
int keyValue = e.KeyChar;
textBox1.Text = Convert.ToChar(keyValue).ToString();
if (keyValue == 13) // DETECT "ENTER"
{
StreamWriter writelog = File.AppendText(#"C:\keylogger.log");
writelog.Write(Environment.NewLine);
writelog.Close();
}
else
{
StreamWriter writelog = File.AppendText(#"C:\keylogger.log");
writelog.Write(Convert.ToChar(keyValue).ToString());
writelog.Close();
}
}

Related

Detect keyboard input and mouse activity on a single form

I have this below form and I want to detect key-strokes and any mouse clicks on the button.
For example, if I press S on my keyboard, message will show START and keypress will display keyboard press. The same thing happen when mouse-click on START button, except that keypress will display START BTN.
Here is my button code. If I only do for button or only IsKeyDown it works fine, but when I combine both in one form, they go haywire.
private void btnStart_Click(object sender, EventArgs e)
{
lblKeypress.Text = "START BTN";
lblmessage.Text = "START";
}
Here is my Keyboard.IsKeyDown code:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Keyboard.IsKeyDown(Key.S))
{
lblKeypress.Text = "Keyboard Press";
lblmessage.Text = "START";
}
}
Please help, thanks.
try this code
private void Form1_KeyDown(object sender,
EventArgs e){
if (e.KeyData == Keys.S){
lblKeypress.Text = "Keyboard Press";
lblmessage.Text = "START";
}
}
Make sure that in your Form you set KeyPreviewProperty to TRUE
In Form1.Designer.cs
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.form_keydown);
private void form_keydown(object sender, KeyEventArgs e)
{
int keyVal = (int)e.KeyValue;
keyValue = -1;
if ((keyVal >= (int)Keys.S))
{
keyValue = (int)e.KeyValue - (int)Keys.S;
lblKeypress.Text = "Keyboard Press";
lblmessage.Text = "START";
}
}
Note:
Ensure you do not have any unrelated WPF namespaces`
(Keyboard.IsKeyDown(Key.S)) is a WPF approach, in WinForms you are better off using combination of e.KeyValue & Keys

C# RichTextBox ReadOnly Event

I have a read only rich text box and an editable text box. The text from the read only is from the editable. They can't be viewed at the same time. When the user presses a key it hides the read only and then selects that position in the editable.
I would like it to enter the key that was pressed into the editable without playing the error "ding"
I'm thinking that an override of the read only error function would be ideal but i'm not sure what that is.
private void EditCode(object sender, KeyPressEventArgs e)
{
int cursor = txtReadOnly.SelectionStart;
tabText.SelectedIndex = 0;
ToggleView(new object(), new EventArgs());
txtEdit.SelectionStart = cursor;
txtEdit.Text.Insert(cursor, e.KeyChar.ToString());
}
Answer:
private void EditCode(object sender, KeyPressEventArgs e)
{
e.Handled = true;
int cursor = txtCleanCode.SelectionStart;
tabText.SelectedIndex = 0;
ToggleView(new object(), new EventArgs());
txtCode.Text = txtCode.Text.Insert(cursor, e.KeyChar.ToString());
txtCode.SelectionStart = cursor + 1;
}
I'll have to make it check if it's a non-control char but that's another deal. Thanks everyone!
One idea is to make the rich text box editable but canceling out all keys:
private void richtextBox1_KeyDown(object sender, KeyEventArgs e)
{
// Stop the character from being entered into the control
e.Handled = true;
// add any other code here
}
Here is one way: Check for <Enter> so the user can still use the navigation keys:
private void txtReadOnly_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true; // no ding for normal keys in the read-only!
txtEdit.SelectionStart = txtReadOnly.SelectionStart;
txtEdit.SelectionLength = txtReadOnly.SelectionLength;
}
}
No need to fiddle with a cursor. Make sure to have:
txtEdit.HideSelection = false;
and maybe also
txtReadOnly.HideSelection = false;
Obviously to keep the two synchronized :
private void txtEdit_TextChanged(object sender, EventArgs e)
{
txtReadOnly.Text = txtEdit.Text;
}
You will need o decide on some way fo r the user to return from editing to viewing. Escape should be reserved for aborting the edit! Maybe Control-Enter?

how to suppress keyboard input

So I am trying to make a program that disables all keyboard input but can still detect when a key is being pressed (doesn't matter which).
I tried using the BlockInput method but it blocked ALL input (mouse and keyboard) and wouldn't allow for further detection of keyboard press.
This is my current code (function is a timer with a 1 tick interval)
private void detect_key_press_Tick(object sender, EventArgs e)
{
Process p = Process.GetCurrentProcess();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
//SetForegroundWindow(h);
if (Keyboard.IsKeyDown(Key.A))
{
//SendKeys.SendWait("k");
this.BackColor = Color.Red;
}
else
{
this.BackColor = Control.DefaultBackColor;
}
}
}
How can I do this please? Thanks.
EDIT
I tried
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
e.Handled = true;
e.SuppressKeyPress = true;
}
but no success. Keys still get proccessed.
I assume you use Windows Forms ?
If you set the KeyPreview on your form to true and create an event on the KeyDown for the form, you can handle the keyboard input that way.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.S) // some accepted key
//Do something with it
else
{
//or cancel the key entry
e.Handled = true;
e.SuppressKeyPress = true;
}
}

Permanent prefix in a TextBox

I am trying to have a permanent prefix input in the textbox. In my case, I want to have the following prefix:
DOMAIN\
So that users can only have to type their username after the domain prefix. It's not something I have to do, or pursue but my question is more out of curiosity.
I was trying to come up with some logic to do this on the TextChangedEvent however, this means I need to know which characters have been deleted where and then pre-append DOMAIN\ to whatever their input is - I can't work out the logic for this so I can't post what I have tried apart from where I got to.
public void TextBox1_TextChanged(object sender, EventArgs e)
{
if(!TextBox1.Text.Contains(#"DOMAIN\")
{
//Handle putting Domain in here along with the text that would be determined as the username
}
}
I've looked on the internet and can't find anything, How do I have text in a winforms textbox be prefixed with unchangable text? was trying to do a similar thing but the answers don't really help.
Any ideas on how I can keep the prefix DOMAIN\ in a TextBox?
Using the KISS principle is indicated here. Trying to catch key presses just won't do anything when the user uses Ctrl+V or the context menu's Cut and Paste commands. Simply restore the text when anything happened that fudged the prefix:
private const string textPrefix = #"DOMAIN\";
private void textBox1_TextChanged(object sender, EventArgs e) {
if (!textBox1.Text.StartsWith(textPrefix)) {
textBox1.Text = textPrefix;
textBox1.SelectionStart = textBox1.Text.Length;
}
}
And help the user avoid editing the prefix by accident:
private void textBox1_Enter(object sender, EventArgs e) {
textBox1.SelectionStart = textBox1.Text.Length;
}
Why not see in the event args of the textChanged what the value was before and the new value and if the Domain\ is not there in the new value, then keep the old one.
Or, why not just show the Domain\ as a label in front of the TextBox and just prepend it in code behind so that the final text is something like Domain\<username>.
Yeah I sort of solved this once I asked the question... I won't delete the question incase anybody else has the same question in the future, because I couldn't find a suitable answer. I set the Text to Domain\ and then used the KeyPress event.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = (textBox1.GetCharIndexFromPosition(Cursor.Position) < 7);
}
I tend to keep working once I ask, instead of letting people do all the work for me :)
How about a reusable custom TextBox control. There are comments in the code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.Prefix = #"DOMAIN\";
}
}
class PrefixedTextBox : TextBox
{
private string _prefix = String.Empty;
public string Prefix
{
get { return _prefix; }
set
{
_prefix = value;
Text = value;
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
// Don't allow Backspace and Delete if the only text is Prefix
if (Text == Prefix && (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete))
e.Handled = true;
// If home key is pressed set cursor just after the prefix
if (e.KeyCode == Keys.Home)
{
e.Handled = true;
SelectionStart = Prefix.Length;
}
// Don't allow cursor to be moved inside Prefix
if (SelectionStart <= Prefix.Length && (e.KeyCode == Keys.Left || e.KeyCode == Keys.Up))
e.Handled = true;
base.OnKeyDown(e);
}
protected override void OnClick(EventArgs e)
{
EnsureCursorPosition();
base.OnClick(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
EnsureCursorPosition();
// this was checked OnKeyDown. This prevents deleting and writing back behaviour
if (Text == Prefix && e.KeyChar == '\b')
e.Handled = true;
base.OnKeyPress(e);
}
protected override void OnKeyUp(KeyEventArgs e)
{
// Yet, some how an invalid text is entered fix it by just displaying the Prefix
if (!Text.StartsWith(Prefix))
Text = Prefix;
base.OnKeyUp(e);
}
private void EnsureCursorPosition()
{
// Never allow cursor position before Prefix
if (SelectionStart < Prefix.Length)
SelectionStart = Text.Length;
}
}

Autocomplete AND preventing new input - combobox

How can I allow the users of my program to type in a value and have it auto-complete, however, I also what to prevent them from entering new data because it would cause the data to be unfindable (unless you had direct access to the database).
Does anyone know how to do this?
The reasoning behind not using just a dropdown style combobox is because entering data by typing it is and then refusing characters that are not part of an option in the list is because it's easier on the user.
If you have used Quickbook's Timer, that is the style of comboboxes I am going for.
Kudos to BFree for the help, but this is the solution I was looking for. The ComboBox is using a DataSet as it's source so it's not a custom source.
protected virtual void comboBoxAutoComplete_KeyPress(object sender, KeyPressEventArgs e) {
if (Char.IsControl(e.KeyChar)) {
//let it go if it's a control char such as escape, tab, backspace, enter...
return;
}
ComboBox box = ((ComboBox)sender);
//must get the selected portion only. Otherwise, we append the e.KeyChar to the AutoSuggested value (i.e. we'd never get anywhere)
string nonSelected = box.Text.Substring(0, box.Text.Length - box.SelectionLength);
string text = nonSelected + e.KeyChar;
bool matched = false;
for (int i = 0; i < box.Items.Count; i++) {
if (((DataRowView)box.Items[i])[box.DisplayMember].ToString().StartsWith(text, true, null)) {
matched = true;
break;
}
}
//toggle the matched bool because if we set handled to true, it precent's input, and we don't want to prevent
//input if it's matched.
e.Handled = !matched;
}
This is my solution, I was having the same problem and modify your code to suit my solution using textbox instead of combobox, also to avoid a negative response after comparing the first string had to deselect the text before comparing again against autocomplet list, in this code is an AutoCompleteStringCollection shiper, I hope this solution will help
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
String text = ((TextBox)sender).Text.Substring(
0, ((TextBox)sender).SelectionStart) + e.KeyChar;
foreach(String s in this.shippers)
if (s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()) ||
e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete)
return;
e.Handled = true;
}
OK, here's what I came up with. Hack? Maybe, but hey, it works. I just filled the combobox with the days of the week (hey, I needed something), and then handle the keypress event. On every key press, I check if that word matches the begining of any word in the AutoCompleteSourceCollection. If it doesn't, I set e.Handled to true, so the key doesn't get registered.
public Form5()
{
InitializeComponent();
foreach (var e in Enum.GetValues(typeof(DayOfWeek)))
{
this.comboBox1.AutoCompleteCustomSource.Add(e.ToString());
}
this.comboBox1.KeyPress += new KeyPressEventHandler(comboBox1_KeyPress);
}
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string text = this.comboBox1.Text + e.KeyChar;
e.Handled = !(this.comboBox1.AutoCompleteCustomSource.Cast<string>()
.Any(s => s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()))) && !char.IsControl(e.KeyChar);
}
EDIT: If you're on .Net 3.5 you'll need to reference System.Linq. If you're on .NET 2.0 then use this instead:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string text = this.comboBox1.Text + e.KeyChar;
foreach (string s in this.comboBox1.AutoCompleteCustomSource)
{
if (s.ToUpperInvariant().StartsWith(text.ToUpperInvariant()))
{
return;
}
}
e.Handled = true;
}
I know I'm about six years late but maybe this can help somebody.
private void comboBox1_Leave(object sender, EventArgs e)
{
if (comboBox1.Items.Contains(comboBox1.Text)) { MessageBox.Show("YE"); }
else { MessageBox.Show("NE"); }
OR
if (comboBox1.FindStringExact(comboBox1.Text) > -1) { MessageBox.Show("YE"); }
else { MessageBox.Show("NE"); }
}

Categories