Get long combination key (password) entered in WPF Window - c#

I'm having a bit of confusion regarding my post here. How to get combination key about 5-10 keys? I'm intended to capture "!qaz$esz" key without double quotes.
My application is a full screen application that prevent access to desktop before entering a right key to enable desktop access. I have kill explorer.exe and disable the Task Manager when the program start and enable it back after combination password is correct:-
private void Window_Loaded(object sender, RoutedEventArgs e)
{
/**
* 1. KILL EXPLORER
* 2. DISABLE KEY TO TERMINATE
* = Alt + F4
* = Win + Tab
* = Win + D
* = etc
* 3. ACCEPT SPECIFIC KEY ONLY TO UNLOCK TO MINIMIZE AND SET TOP = FALSE
*
*
* **/
RegistryKey regkey = SetKey(TaskManager.Disabled);
regkey.Close();
}
public static RegistryKey SetKey(TaskManager command)
{
RegistryKey mKey;
string subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
mKey = Registry.CurrentUser.CreateSubKey(subKey);
switch (command)
{
case TaskManager.Enabled:
mKey.SetValue("DisableTaskMgr", 0);
break;
case TaskManager.Disabled:
mKey.SetValue("DisableTaskMgr", 1);
break;
}
return mKey;
}
But something must be lack on my code where I cannot detect the combination code that more to password.
Below code are what I'm testing to see if my entered key is captured.
public MainWindow()
{
InitializeComponent();
AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent);
}
private void HandleKeyDownEvent(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift))
{
MessageBox.Show("CTRL + SHIFT + TAB trapped"); // Working
}
if (e.Key == Key.Tab && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
MessageBox.Show("CTRL + TAB trapped"); // Working
}
if (e.Key == Key.F4 && Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
{
MessageBox.Show("ALT + F4 trapped"); // Not working
}
if (e.Key == Key.D && Keyboard.Modifiers.HasFlag(ModifierKeys.Windows))
{
MessageBox.Show("WIN + D trapped"); // Not working
}
if ((Keyboard.IsKeyDown(Key.LeftShift) && e.Key == Key.D1) && e.Key ==Key.Q && e.Key == Key.A && e.Key == Key.Z && e.Key == Key.D4 && e.Key == Key.E && e.Key == Key.S && e.Key == Key.Z)
{
MessageBox.Show("COMBOKEY"); // Not working
// RUN EXPLORER
// ENABLE TASK MANAGER
}
}
What is not settle is WINLOGO + D, ALT + TAB, ALT + F4 and LONG COMBINATION KEY.
I have try some of the code from here:-
https://stackoverflow.com/a/5750757/3436326
https://stackoverflow.com/a/17088823/3436326
I have see some discussion/posting/article on writing to LowLevelAPI. I'm not familiar accessing low level API and apply it on WPF application:-
http://www.tamas.io/c-disable-ctrl-alt-del-alt-tab-alt-f4-start-menu-and-so-on/
https://www.codeproject.com/articles/14485/low-level-windows-api-hooks-from-c-to-stop-unwante

e.Key == Key.Q && e.Key == Key.A
If e.Key is equal to Key.Q, it cannot be equal to Key.A at the same time. That’s why it’s not working. What you want to detect is the sequence of those keys, and since you only have a key listener, you have to take care of managing the state yourself:
private int passwordState = 0;
private void HandleKeyDownEvent(object sender, KeyEventArgs e)
{
// other checks
else if (Keyboard.IsKeyDown(Key.LeftShift) && e.Key == Key.D1)
passwordState = 1; // first key of the password
else if (passwordState == 1 && e.Key == Key.Q)
passwordState = 2;
else if (passwordState == 2 && e.Key == Key.A)
passwordState = 3;
else if (passwordState == 3 && e.Key == Key.Z)
passwordState = 4;
else if (passwordState == 4 && e.Key == Key.D4)
passwordState = 5;
else if (passwordState == 5 && e.Key == Key.E)
passwordState = 6;
else if (passwordState == 6 && e.Key == Key.S)
passwordState = 7;
else if (passwordState == 7 && e.Key == Key.Z)
{
passwordState = 0;
// correct password
MessageBox.Show("COMBOKEY");
}
else
passwordState = 0; // some other/unexpected key: reset password state
}
But that is really annoying to maintain, so why don’t you have a special key combination instead that simply shows a modal prompt for the user to enter the password? Yes, you would show the user a clear password prompt then that they could accidentally discover, but what’s the problem with that?

Related

How to validate TextBox to allow only 1 decimal point - Windows Phone 8

I want to validate TextBox to allow only 1 decimal point and up to 2 decimal places after it. For number validate only, i am using InputScope="Number", but it can not avoid pasting letters, so i need any validation for paste too (or just disable pasting). For example the user must be able to insert numbers like 23, 23.1, 23.12 and NOT 23.123, 23.1.2 etc.
private void tb1_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key >= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9 || e.Key == Windows.System.VirtualKey.Decimal || e.Key == Windows.System.VirtualKey.GamepadY)
{
string strkey = e.Key.ToString().Substring(e.Key.ToString().Length - 1, e.Key.ToString().Length - (e.Key.ToString().Length - 1));
if (e.Key >= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9)
{
TextBox tb = sender as TextBox;
int cursorPosLeft = tb.SelectionStart;
int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
string result1 = tb.Text.Substring(0, cursorPosLeft) + strkey + tb.Text.Substring(cursorPosRight);
string[] parts = result1.Split('.');
if (parts.Length > 1)
{
if (parts[1].Length > 2 || parts.Length > 2)
{
e.Handled = true;
}
}
}
if (((TextBox)sender).Text.Contains(".") && e.Key == Windows.System.VirtualKey.Decimal)
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
if (e.Key >= Windows.System.VirtualKey.A && e.Key <= Windows.System.VirtualKey.Z ||
e.Key == Windows.System.VirtualKey.Space)
{
e.Handled = true;
}
}

How to disable certain combination keys (eg. Shift + "certain number key")

I'm created a telephone keypad which consists of 0-9 plus hash key (#) and star key (*). I was able to disable other keys except those number keys so that when user type in the textbox provided, it will only allow number keys. Since # is the combination of Shift+3 and * is the combination of Shift+8, my problem is I can't disable other combination key except those two. So, is there any way to handle this problem in order to just allow Shift+3 and Shift+8 only?
private void NumDisplayBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
//Determine whether the keystroke is a number from the top of the keyboard
if (e.Key < Key.D0 || e.Key > Key.D9)
//Determine whether the keystroke is a number from the keypad
if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
e.Handled = true;
if (e.Key == Key.Space) //Disable the space key
e.Handled = true;
//Enable the following keys
if (e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Left || e.Key == Key.Right)
e.Handled = false;
//Determine whether the keystroke is # or *
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.D3))
e.Handled = false;
}

WPF Key is digit or number

I have previewKeyDown method in my window, and I'd like to know that pressed key is only A-Z letter or 1-0 number (without anyF1..12, enter, ctrl, alt etc - just letter or number).
I've tried Char.IsLetter, but i need to give the char, so e.key.ToString()[0] doesn't work, because it is almost everytime a letter.
Something like this will do:
if ((e.Key >= Key.A && e.Key <= Key.Z) || (e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
Of course you will also have to check that no modifier keys like CTRL are pressed according to your requirements.
e.Key is giving you a member of the enum System.Windows.Input.Key
You should be able to do the following to determine whether it is a letter or a number:
var isNumber = e.Key >= Key.D0 && e.Key <= Key.D9;
var isLetter = e.Key >= Key.A && e.Key <= Key.Z;
In your specific case the answer provided by Jon and Jeffery is probably best, however if you need to test your string for some other letter/number logic then you can use the KeyConverter class to convert a System.Windows.Input.Key to a string
var strKey = new KeyConverter().ConvertToString(e.Key);
You'll still need to check to see if any modifier keys are being held down (Shift, Ctrl, and Alt), and it should also be noted that this only works for Letters and Numbers. Special characters (such as commas, quotes, etc) will get displayed the same as e.Key.ToString()
try this, it works.
private void txbNumber_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key >= Key.D0 && e.Key <= Key.D9) ; // it`s number
else if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) ; // it`s number
else if (e.Key == Key.Escape || e.Key == Key.Tab || e.Key == Key.CapsLock || e.Key == Key.LeftShift || e.Key == Key.LeftCtrl ||
e.Key == Key.LWin || e.Key == Key.LeftAlt || e.Key == Key.RightAlt || e.Key == Key.RightCtrl || e.Key == Key.RightShift ||
e.Key == Key.Left || e.Key == Key.Up || e.Key == Key.Down || e.Key == Key.Right || e.Key == Key.Return || e.Key == Key.Delete ||
e.Key == Key.System) ; // it`s a system key (add other key here if you want to allow)
else
e.Handled = true; // the key will sappressed
}
Add a reference to Microsoft.VisualBasic and use the VB IsNumeric function, combined with char.IsLetter().
bit of a cludge but it works :)
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
Regex R = new Regex("^([A-Z]|[0-9]){1}$");
var strKey = new KeyConverter().ConvertToString(e.Key);
if(strKey.Length > 1 )
{
strKey = strKey.Replace("NumPad", "").Replace("D", "");
}
if (strKey.Length == 1)
{
if (!R.IsMatch(strKey))
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
}
Can you put some code to show what you intend? Shouldn't this work for you
if(e.key.ToString().Length==1)
`Char.IsLetter(e.key.ToString()[0])`
else
//

detect Ctrl + Enter

(using WPF)
i try to detect when Ctrl + Enter gets hit.
so i tried this code:
if (e.Key == Key.Return && (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl))
{
//Do Something
}
Obviously this is not correct, as it does not work.
Could anyone help me out, explaining what the right way should be ?
thanx
Obviously e.Key can't be equal to more than one different value in the same event.
You need to handle one of the events that uses KeyEventArgs, there you'll find properties such as Control and Modifiers that will help you detect combinations.
The KeyPress event, which uses KeyPressEventArgs, just doesn't have sufficient information.
Drat, you said WPF didn't you. It looks like you need e.KeyboardDevice.Modifiers.
I think you need a SpecialKey Handler.
I googled a bit a found a solution here.
Following code from the referred link may solve your problem:
void SpecialKeyHandler(object sender, KeyEventArgs e)
{
// Ctrl + N
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.N))
{
MessageBox.Show("New");
}
// Ctrl + O
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.O))
{
MessageBox.Show("Open");
}
// Ctrl + S
if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.S))
{
MessageBox.Show("Save");
}
// Ctrl + Alt + I
if ((Keyboard.Modifiers == (ModifierKeys.Alt | ModifierKeys.Control)) && (e.Key == Key.I))
{
MessageBox.Show("Ctrl + Alt + I");
}
}
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Enter)
if (e.KeyChar == 10)
{
///Code
}
Or
if ((Char)e.KeyChar == '\n')
{
///Code
}

Silverlight textbox to accept only decimals

I have a Silverlight app with a textbox whose input I want to limit to decimal numbers only. Searching the web I came across the following possible solution (curiously in different places with different people claiming authorship of the same lines of code)
It appears to work well except that after at least 1 numeral has been entered it will then allow the letter 'd' in either upper or lower case to be entered, I can't figure out why that is and thus can't figure out how to prevent that from happening. Could anyone please provide a solution. Many thanks.
private void Unit_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
}
var thisKeyStr = "";
if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
{
thisKeyStr = ".";
}
else
{
thisKeyStr = e.Key.ToString().Replace("D", "").Replace("NumPad", "");
}
var s = (sender as TextBox).Text + thisKeyStr;
var rStr = "^[0-9]+[.]?[0-9]*$";
var r = new Regex(rStr, RegexOptions.IgnoreCase);
e.Handled = !r.IsMatch(s);
}
You could try the following:
Replace the else with else if (e.Key != Key.D) or
set the Handled property like this:
e.Handled = !r.IsMatch(s) || string.IsNullOrEmpty(thisKeyStr);
// also possible:
e.Handled = !r.IsMatch(s) || e.Key == Key.D;
here is a easier code optimized. NO object creation; NO string comparision and NO regex validation
private static void TextBox_KeyDown(object sender, KeyEventArgs e)
{
//platform code for Hyphen which is not same as Subtract symbol but in our case both give same meaning
const int KEYCODE_Hyphen_OnKeyboard = 189;
const int KEYCODE_Dot_OnKeyboard = 190;
const int KEYCODE_Dot_OnNumericKeyPad = 110;
e.Handled = !(
(!( //No modifier key must be pressed
(Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift
|| (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control
|| (Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt
)
&& ( //only these keys are supported
(e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
|| e.Key == Key.Subtract || e.Key == Key.Add || e.Key == Key.Decimal
|| e.Key == Key.Home || e.Key == Key.End || e.Key == Key.Delete
|| e.Key == Key.Tab || e.Key == Key.Enter || e.Key == Key.Escape || e.Key == Key.Back
|| (e.Key == Key.Unknown && (
e.PlatformKeyCode == KEYCODE_Hyphen_OnKeyboard
|| e.PlatformKeyCode == KEYCODE_Dot_OnKeyboard || e.PlatformKeyCode == KEYCODE_Dot_OnNumericKeyPad
)
)
)
)
);
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
bool isDigit = e.Key >= Key.D0 && e.Key < Key.D9 || e.Key == Key.NumPad0 || e.Key == Key.NumPad1 || e.Key == Key.NumPad2 || e.Key == Key.NumPad3 || e.Key == Key.NumPad4 || e.Key == Key.NumPad5 || e.Key == Key.NumPad6 ||
e.Key == Key.NumPad7 || e.Key == Key.NumPad8 || e.Key == Key.NumPad9 ||e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Left || e.Key == Key.Right;
if (isDigit) { }
else
e.Handled = true;
}

Categories

Resources