Custom TextBox Control that Switches Keyboard Language Automatically c# WPF - c#

i need to make something like that
http://www.codeproject.com/Articles/301832/Custom-Text-box-Control-that-Switch-keyboard-langu
but for WPF and C#
i'v tried to do it with a simple if statement but i was have to put another textbox like that
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
textBox1.Focus();
if (textBox1.Text == "Q" || textBox1.Text == "q")
{
textBox2.Text = textBox2.Text+ "ض";
textBox1.Text = "";
}
else if (textBox1.Text == "W" || textBox1.Text == "w")
{
textBox2.Text = textBox2.Text + "ص";
textBox1.Text = "";
}
// and so ..
}
it works but i want to do something like the link above

You can do that in WPF by creating a new custom Control that inherits TextBox. In that Create a new TextLanguage Property and Override the OnKeyDown method
namespace WpfApplication
{
public enum TextLanguage
{
English,
Arabic
}
public class CustomTextBox : TextBox
{
public TextLanguage TextLanguage { get; set; }
protected override void OnKeyDown(KeyEventArgs e)
{
if (TextLanguage != WpfApplication.TextLanguage.English)
{
e.Handled = true;
if (Keyboard.Modifiers == ModifierKeys.Shift)
{
// Shift key is down
switch (e.Key)
{
case Key.Q:
AddChars("ص");
break;
// Handle Other Cases too
default:
e.Handled = false;
break;
}
}
else if (Keyboard.Modifiers == ModifierKeys.None)
{
switch (e.Key)
{
case Key.Q:
AddChars("ض");
break;
// Handle Other Cases too
default:
e.Handled = false;
break;
}
}
}
base.OnKeyDown(e);
}
void AddChars(string str)
{
if (SelectedText.Length == 0)
AppendText(str);
else
SelectedText = str;
this.SelectionLength = 0;
this.CaretIndex = Text.Length;
}
}
}

Related

C# Help Creating Custom Control

Am trying to make a custom control which accepts input depending in the selected option. i want to limit the decimal point to only one so the user wont enter multiple "." how can i do this?
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace DT_Controls
{
public enum Options { Any, Alphabets, Alpha_Numeric, Numeric }
public class TextBox_Pro : TextBox
{
Options _Opt = 0;
bool _Flag = false;
int Count = 0;
[Category("Behavior")]
[Description("If set as true will accept decimal values when SetOption is Numeric")]
public bool AcceptDecimal
{
get { return _Flag; }
set { _Flag = value; }
}
[Category("Behavior")]
[Description("Controls the type of value being entered into the TextBox_Pro")]
public Options SetOption
{
get { return _Opt; }
set { _Opt = value; }
}
public TextBox_Pro()
{
this.KeyPress += TextBox_Pro_KeyPress;
}
private void TextBox_Pro_KeyPress(object sender, KeyPressEventArgs e)
{
if (Convert.ToInt32(e.KeyChar) == 8)
return;
switch (_Opt)
{
case Options.Numeric:
if (_Flag == true)
if (Convert.ToInt32(e.KeyChar) == 46)
return;
if (char.IsDigit(e.KeyChar) == false)
{
MessageBox.Show("Enter Numeric Values Only");
e.Handled = true;
}
break;
case Options.Alphabets:
if(char.IsLetter(e.KeyChar)==false && Convert.ToInt32(e.KeyChar) != 32)
{
MessageBox.Show("Enter Only Aplhabets");
e.Handled = true;
}
break;
case Options.Alpha_Numeric:
if (char.IsLetterOrDigit(e.KeyChar) == false)
{
MessageBox.Show("Enter Only Alphabets Or Numbers");
e.Handled = true;
}
break;
}
}
}
}
example i do not want user to enter 12.....123 i want user to enter 12.123 and after one . it should disable the flag, but when i do it it wont let me allow to enter any "." even after removing the "."
Easier than setting any flags is checking if your TextBox already contains any "." with the built-in function. So, replace the following code:
if (_Flag == true)
if (Convert.ToInt32(e.KeyChar) == 46)
return;
with:
if (Convert.ToInt32(e.KeyChar) == 46)
{
if (this.Text.Contains("."))
{
e.Handled = true;
}
return;
}
This way you can also check for other inconsistencies, like checking if the text in the TextBox starts with a "."
Different cultures use different number decimal separators, so it's best to read that from the CultureInfo.CurrentCulture.NumberFormat rather than hardcoding a value. Because you are inheriting from TextBox you can override OnKeyPress instead of subscribing to the KeyPress event. The following example also automatically displays 0. if the decimal separator is the first character.
[ToolboxBitmap(typeof(TextBox))]
public class TextBoxPro
: TextBox
{
static NumberFormatInfo s_numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat;
public static readonly string s_decimalSeparator = s_numberFormatInfo.NumberDecimalSeparator;
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (ReadOnly)
return;
var keyChar = e.KeyChar;
var keyString = keyChar.ToString();
if (keyString == s_decimalSeparator)
{
if (IsAllSelected)
{
e.Handled = true;
Text = "0.";
SelectionStart = 2;
}
else if (Text.Contains(s_decimalSeparator))
e.Handled = true;
}
}
private bool IsAllSelected
{
get { return SelectionLength == TextLength; }
}
}

How to pass a TextBox Object as a parameter to a method using c#

I want to pass a textbox object to a function where this function then validated the key processed on "KeyPress" event.
I have created a method inside a class called "common" like this
public void PreventInput(Telerik.WinControls.UI.RadTextBox tb, KeyPressEventArgs e, bool isDouble = true)
{
string input = tb.Text;
if (isDouble)
{
if ((Char.IsDigit(e.KeyChar))
|| (Char.IsControl(e.KeyChar))
|| ((e.KeyChar == '.') && (input.Contains(".") == false))
)
{
return;
}
}
else
{
if ((Char.IsDigit(e.KeyChar))
|| (Char.IsControl(e.KeyChar))
)
{
return;
}
}
e.Handled = true;
}
Then when I want to call this function inside keyPress Event, I do this
private void InputUnitPrice_KeyPress(object sender, KeyPressEventArgs e)
{
Common.PreventInput(sender, e, true);
}
but for some reason calling this method is giving me an error.
cannot convert from 'object' to 'Telerik.WinControls.UI.RadTextBox
RM.Common.PreventInput(Telerik.WinControls.UI.RadTextBox, System.Windows.Forms.KeyPressEventArgs, bool)' has some invalid arguments
this code works with no issue but I am trying to avoid re-writing the code over and over everytime I want to restrict an input to number only
private void InputUnitPrice_KeyPress(object sender, KeyPressEventArgs e)
{
string input = (sender as Telerik.WinControls.UI.RadTextBox).Text;
if ((Char.IsDigit(e.KeyChar))
|| (Char.IsControl(e.KeyChar))
|| ((e.KeyChar == '.') && (input.Contains(".") == false))
){
return;
}
e.Handled = true;
}
The question is how to get the PreventInput method to work without the errors.
Edited
based on the feedback below, I tried the following (and still did not work)
public bool PreventInput(string input, KeyPressEventArgs e, bool isDouble = true)
{
if (isDouble)
{
if ((Char.IsDigit(e.KeyChar))
|| (Char.IsControl(e.KeyChar))
|| ((e.KeyChar == '.') && (input.Contains(".") == false))
)
{
return false;
}
}
else
{
if ((Char.IsDigit(e.KeyChar))
|| (Char.IsControl(e.KeyChar))
)
{
return false;
}
}
return true;
}
and I call it like this
e.Handled = Common.PreventInput((sender as Telerik.WinControls.UI.RadTextBox).Text, e, true);
You need to cast the sender from Object to RadTextBox:
var txt = (Telerik.WinControls.UI.RadTextBox) sender;
Common.PreventInput(txt, e, true);
But why do you want to pass the control instead of just the text? The method should validate the input and leave the action to it's caller. On that way it is reusable and doesn't depend on any control.
So you could write it in this way:
public bool ValidateInput(string input, bool isDouble = true)
{
bool isValid;
// insert your logic here ...
return isValid;
}
now handle the return value as desired:
var txt = (Telerik.WinControls.UI.RadTextBox) sender;
e.Handled = Common.ValidateInput(txt.Text, true);
Convert the object to a textbox first:
Common.PreventInput(sender as Telerik.WinControls.UI.RadTextBox, e, true);
Your logic can be somewhat simplified a little as well:
public void PreventInput(Telerik.WinControls.UI.RadTextBox tb,
KeyPressEventArgs e, bool isDouble = true)
{
string input = tb.Text ?? string.Empty;
if (Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar))
{
return;
}
if (isDouble && e.KeyChar == '.' && !input.Contains("."))
{
return;
}
e.Handled = true;
}

Restrict Textbox to 1 decimal place. Winform C#

I am developing a winform application using c# I have successfully implemented a way to restrict textbox to two decimal places. How can I do it to one decimal place. ?
My code for two decimal places.\
private void txtHraRep_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{
if (Regex.IsMatch(
txtHraRep.Text,
"^\\d*\\.\\d{2}$")) e.Handled = true;
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
Changing to "^\d*\.\d{1}$")) e.Handled = true;
output
You can do this without regex by just checking where the decimal separator is in your text and then making sure that is 2 less than the length of the string (1 decimal place and 1 less for array length)
var decSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
var idx = txtBasic.Text.IndexOf(decSeparator);
if(idx + 2 >= txtBasic.Text.Length)
...
Instead of using a TextBox control for the input, look at using a MaskedTextbox control for your input. This will alleviate any self validation of the input and can show the users what input can be expected of them with messages as to why their input was not correct.
More information about the MaskedTextbox control:
MaskedTextbox
MaskedTextbox.Mask property
MSDN Walkthrough: Working with the MaskedTextBox Control
I just tried
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
{
if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{
if (Regex.IsMatch(
textBox1.Text,
"^\\d*\\.\\d{1}$")) e.Handled = true;
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
}
and it worked as it should. It restricted the input to one digit after the decimal point.
But you could enter more than one decimal point and then also more digits.
So you can either try
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || ((e.KeyChar == '.') && (textBox1.Text.IndexOf('.')== -1 )))
{
if (Regex.IsMatch(
textBox1.Text,
"^\\d*\\.\\d{1}$")) e.Handled = true;
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
or something like
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || ((e.KeyChar == '.') && (textBox1.Text.IndexOf('.')== -1 )))
{
if (textBox1.Text.IndexOf('.') > 0)
{
if (textBox1.Text.IndexOf('.') < textBox1.Text.Length - 1)
e.Handled = true;
}
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
Create A new TextBox that inherit TextBox like
[DefaultBindingProperty("Text")]
[DefaultProperty("Text")]
[DefaultEvent("ValueChanged")]
public class SpecializedTextBox : TextBox
{
private bool _allowNegativeSign = false;
public bool AllowNegativeSign
{
get { return _allowNegativeSign; }
set { _allowNegativeSign = value; }
}
public decimal? DecimalValue
{
get
{
decimal k;
if (decimal.TryParse(this.Text, out k))
return k;
else
return null;
}
set
{
if (value.HasValue)
this.Text = value.Value.ToString();
else
this.Text = "";
}
}
private void This_TextChanged(object sender, EventArgs e)
{
string s = base.Text;
int cursorpos = base.SelectionStart;
bool separatorfound = false;
for (int i = 0; i < s.Length; )
{
if (char.IsNumber(s[i]))
i++;
else if (AllowNegativeSign && i < System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.NegativeSign.Length && s.StartsWith(System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.NegativeSign))
i++;
else if (!separatorfound && s[i].ToString() == System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator)
{
separatorfound = true;
i++;
}
else
{
s = s.Remove(i, 1);
if (i < cursorpos)
cursorpos--;
}
}
if (base.Text != s)
{
base.Text = s;
base.SelectionStart = cursorpos;
base.SelectionLength = 0;
}
if (ValueChanged != null)
ValueChanged(this, EventArgs.Empty);
}
public event EventHandler ValueChanged;
private void InitializeComponent()
{
this.SuspendLayout();
//
// SpecializedTextBox
//
this.TextChanged += new System.EventHandler(this.This_TextChanged);
this.ResumeLayout(false);
}
public SpecializedTextBox()
: base()
{
InitializeComponent();
}
}
now use this text box and use DecimalValue to set or get your value
try:
List<string> doubleList = new List<string>(new string[]
{
"12345",
"1234.5",
"123.45",
"12.345",
"1.2345",
"1.2",
"1.23",
"1.234",
"1.23.45",
"12.3",
"123.4",
}) { };
private void button1_Click(object sender, EventArgs e)
{
foreach (var x in doubleList)
{
int countNumber = Regex.Matches(x, #"[0-9]").Count;
int countOfDot = Regex.Matches(x, #"\.").Count;
if (countOfDot == 1 && countNumber != 0) //contains "." and any digit
{
Console.WriteLine(x);
}
else if (countOfDot == 0 && countNumber != 0) //not contains "." and any digit
{
Console.WriteLine(x);
}
else
{
//do nothing . . .
}
}
}
output:
all except for **1.23.45** (2dots)

Negative Numbers in C# TextBox

I have gone through the questions here and have found the answer for making a textbox accept only numeric values with one decimal and negative sign at the beginning.
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '-')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (e.KeyChar == '-' && (sender as TextBox).Text.Length > 0)
{
e.Handled = true;
}
However I do have one problem. Suppose the user typed a number:
123455789764
And then he realizes that the number is negative. He goes back to the beginning and tried to type in the negative sign, only to find that it's not working. Is there a way to address this problem instead of getting the user to delete the number that he typed, add the negative number and retype the number again?
Try this:
Regex reg = new Regex(#"^-?\d+[.]?\d*$");
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsControl(e.KeyChar)) return;
if (!reg.IsMatch(textBox1.Text.Insert(textBox1.SelectionStart, e.KeyChar.ToString()) + "1")) e.Handled = true;
}
For the suggestion of keyboardP, I add this code to fully prevent non-numeric value, I think you should try TextBox.ShortcutsEnabled = false; because I don't think user needs any kind of copying and pasting numeric data.
Regex reg = new Regex(#"^-?\d+[.]?\d*$");
bool textChangedByKey;
string lastText;
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsControl(e.KeyChar)) return;
if (!reg.IsMatch(textBox1.Text.Insert(textBox1.SelectionStart, e.KeyChar.ToString()) + "1"))
{
e.Handled = true;
return;
}
textChangedByKey = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (!textChangedByKey)
{
if (!reg.IsMatch(textBox1.Text))
{
textBox1.Text = lastText;
return;
}
}
else textChangedByKey = false;
lastText = textBox1.Text;
}
I've tried using Undo() method with some resetting SelectedText, however it's a little bad, even the way above doesn't bring a good visual effect (you can see the text changing and restoring to the valid value when try pasting text into the numeric textbox).
Evaluate characters only when some "OK" or "Submit" button is clicked, not on every keystroke
Use a regular expression to check the entire text for validity, not just the typed character OR
Try to parse the text into a long using Int64.TryParse and evaluate the bool result of the call.
Having read all the above: Why not simply use a NumericUpDown control?
Instead of checking the length of the string (and discarding "-" when it's non-zero), you could check the cursor position and discard "-" when the cursor is not a the beginning or when there is already a "-" at the beginning.
But doing the whole check later during submission instead of swallowing keystrokes might be better UX.
I think that relying on textbox events is a better approach to your problem. In any case, you can continue using your methodology and complement it with events to account for the heading "-" issue. This code deletes any dashes from the textbox unless being in the first position:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 0)
{
if (textBox1.Text.Contains("-") && (textBox1.Text.Substring(0, 1) != "-" || textBox1.Text.Split('-').Length > 2))
{
bool headingDash = false;
if (textBox1.Text.Substring(0, 1) == "-")
{
headingDash = true;
}
textBox1.Text = textBox1.Text.Replace("-", "");
if (headingDash)
{
textBox1.Text = "-" + textBox1.Text;
}
}
}
}
This works for me (although you may consider some modification depending on how you want to handle decimal separators (as number format is dependant on CurrentCulture settings)
This accepts only numbers, the length and further formatting of input (e.g. only one digit allowed before decimal separator) is not addressed, although I think it can be modiffied to do that.
public enum NumericTextBoxType { TDecimal = 1, TByte, TShort, TInt, TLong }
public class NumericTextBox : TextBox
{
#region ARRAYS
private static readonly Keys[] separators =
{
Keys.Decimal,
Keys.Oemcomma,
Keys.OemPeriod
};
private static readonly Keys[] allowed =
{
Keys.D1,
Keys.D2,
Keys.D3,
Keys.D4,
Keys.D5,
Keys.D6,
Keys.D7,
Keys.D8,
Keys.D9,
Keys.D0,
Keys.NumPad0,
Keys.NumPad1,
Keys.NumPad2,
Keys.NumPad3,
Keys.NumPad4,
Keys.NumPad5,
Keys.NumPad6,
Keys.NumPad7,
Keys.NumPad8,
Keys.NumPad9,
Keys.Decimal,
Keys.Oemcomma,
Keys.OemPeriod,
Keys.OemMinus,
Keys.Subtract,
Keys.Back,
Keys.Delete,
Keys.Tab,
Keys.Enter,
Keys.Up,
Keys.Down,
Keys.Left,
Keys.Right
};
private static readonly Keys[] intallowed =
{
Keys.D1,
Keys.D2,
Keys.D3,
Keys.D4,
Keys.D5,
Keys.D6,
Keys.D7,
Keys.D8,
Keys.D9,
Keys.D0,
Keys.NumPad0,
Keys.NumPad1,
Keys.NumPad2,
Keys.NumPad3,
Keys.NumPad4,
Keys.NumPad5,
Keys.NumPad6,
Keys.NumPad7,
Keys.NumPad8,
Keys.NumPad9,
Keys.OemMinus,
Keys.Subtract,
Keys.Back,
Keys.Delete,
Keys.Tab,
Keys.Enter,
Keys.Up,
Keys.Down,
Keys.Left,
Keys.Right
};
#endregion ARRAYS
#region PROPERTY NumericTextBoxType
private NumericTextBoxType _NumericTextBoxType = NumericTextBoxType.TDecimal;
public NumericTextBoxType NumericTextBoxType
{
get
{
return
_NumericTextBoxType;
}
set
{
_NumericTextBoxType = value;
}
}
#endregion PROPERTY NumericTextBoxType
#region PROPERTY AllowMinus
public bool AllowMinus { get; set; }
#endregion
string prvText = "";
int prevSelStart = 0;
public NumericTextBox()
: base()
{
this.NumericTextBoxType = NumericTextBoxType.TDecimal;
this.AllowMinus = true;
}
#region EVENT METHOD OnKeyDown
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Modifiers == Keys.Control)
{
prvText = this.Text;
prevSelStart = this.SelectionStart;
return;
}
// ignore not allowed
if (NumericTextBoxType != NumericTextBoxType.TDecimal)
{
if (!intallowed.Contains(e.KeyCode)) e.SuppressKeyPress = true;
}
else
{
if (!allowed.Contains(e.KeyCode)) e.SuppressKeyPress = true;
else if (separators.Contains(e.KeyCode))
{
NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
int selLength = this.SelectionLength;
int selStart = this.SelectionStart;
if (!this.Text.Remove(selStart, selLength).Contains(decimalSeparator))
{
this.Text = this.Text
.Remove(selStart, selLength)
.Insert(this.SelectionStart, decimalSeparator);
this.SelectionStart = selStart + decimalSeparator.Length;
}
e.SuppressKeyPress = true;
}
}
// ignore minus if not first or not allowed
if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract)
{
if (!this.AllowMinus) e.SuppressKeyPress = true;
else if (NumericTextBoxType == NumericTextBoxType.TByte) e.SuppressKeyPress = true;
else if (this.SelectionStart > 0) e.SuppressKeyPress = true;
}
prvText = this.Text;
prevSelStart = this.SelectionStart;
}
#endregion EVENT METHOD OnKeyDown
#region METHOD OnTextChanged
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
// don't allow incorrect paste operations
if (Regex.IsMatch(this.Text, (!AllowMinus ? "[-" : "[") + #"^\d.,]") ||
Regex.Matches(this.Text, #"[.,]").Count > 1)
{
this.Text = prvText;
this.SelectionStart = prevSelStart;
}
}
#endregion
}

Hide password text

I have a textbox using UseSystemPasswordChar, so it will not display the password that the user enters. The issue is that the password is still able to be read by something like Spy++. I'm looking for a way to hide this like they do in the password fields in the Services.msc > Log On tab.
Here is what I've got so far.
You can improve this by having some unique events to indicate whether a pressed key has been accepted, if InputFilter or RealText has been changed, etc...
Another great thing to improve would be the default usage of InputFilter, because working with char and Keys doesn't really work for many special keys. For example - at the moment, if you press Alt+F4 when the PasswordBox is in focus, it will type in 's'... So there's a bag of bugs to fix.
And lastly, there's probably a more elegant way to handle capital vs non-capital letters input than what I did there.
So here it is:
public class PasswordBox : TextBox
{
private string _realText;
public string RealText
{
get { return this._realText; }
set
{
var i = this.SelectionStart;
this._realText = value ?? "";
this.Text = "";
this.Text = new string('*', this._realText.Length);
this.SelectionStart = i > this.Text.Length ? this.Text.Length : i;
}
}
private Func<KeyEventArgs, bool> _inputFilter;
public Func<KeyEventArgs, bool> InputFilter
{
get { return this._inputFilter; }
set { this._inputFilter = value ?? (e => true); }
}
public PasswordBox()
{
this.RealText = "";
this.InputFilter = e => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".Any(c => c == e.KeyValue);
}
protected override void OnKeyDown(KeyEventArgs e)
{
e.SuppressKeyPress = true;
switch (e.KeyCode)
{
case Keys.Back:
if (this.SelectionStart > 0 || this.SelectionLength > 0)
{
this.RealText = this.SelectionLength == 0
? this.RealText.Remove(--this.SelectionStart, 1)
: this.RealText.Remove(this.SelectionStart, this.SelectionLength);
}
break;
case Keys.Delete:
if (this.SelectionStart == this.TextLength)
{
return;
}
this.RealText = this.RealText.Remove(this.SelectionStart, this.SelectionLength == 0 ? 1 : this.SelectionLength);
break;
case Keys.X:
case Keys.C:
case Keys.V:
if (e.Control)
{
return;
}
goto default;
case Keys.Right:
case Keys.Left:
case Keys.Up:
case Keys.Down:
case Keys.Shift:
case Keys.Home:
case Keys.End:
e.SuppressKeyPress = false;
base.OnKeyDown(e);
break;
default:
if (e.Control)
{
e.SuppressKeyPress = false;
base.OnKeyDown(e);
break;
}
if (this.InputFilter(e))
{
var c = (char)e.KeyValue;
if (e.Shift == IsKeyLocked(Keys.CapsLock))
{
c = char.ToLower(c);
}
this.RealText = this.RealText.Remove(this.SelectionStart, this.SelectionLength)
.Insert(this.SelectionStart, c.ToString());
this.SelectionStart++;
}
break;
}
}
}
So try something like this
private string realpass = "";
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (Char) Keys.Back)
realpass += realpass.Substring(0, realpass.Length - 2);
realpass += e.KeyChar.ToString();
textBox1.Text = "";
for (int i = 0; i < realpass.Length; i++)
textBox1.Text += "*";
}
You should not use your own dialog if you intend to collect Windows/domain user credentials. You should use what Windows provides via PInvoke or simply use a wrapper like this,
http://weblogs.asp.net/hernandl/archive/2005/11/21/usercredentialsdialog.aspx
and this,
http://credentials.codeplex.com/

Categories

Resources