KeyPress event equivalent in WPF - c#

i have the following code in WPA, and i am trying to convert it to WPF. I tried Keydown instead of Keypress and changed, for example,
(e.keyChar == '-') to (e.key == e.Subtract):
its not working the same
I cant find the equal sign within e.key
first code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
foreach (TextBox tb in this.Controls.OfType<TextBox>())
{
tb.Enter += textBox_Enter;
}
}
void textBox_Enter(object sender, EventArgs e)
{
focusedTextbox = (TextBox)sender;
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '+')
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 1;
e.Handled = true;
}
else if (e.KeyChar == '-')
{
if (focusedTextbox != null)
{
if (focusedTextbox.Text == "")
{
e.Handled = false;
}
else
{
e.Handled = true;
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 2;
}
}
}
else if (e.KeyChar == '*')
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 3;
e.Handled = true;
}
else if (e.KeyChar == '/')
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 4;
e.Handled = true;
}
else if (e.KeyChar == '=')
{
e.Handled = true;
operand2.Real = getOperand.Real;
operand2.Imag = getOperand.Imag;
switch (flag1)
{
case 1:
operand1 = operand1 + operand2;
break;
case 2: operand1 = operand1 - operand2;
break;
case 3:
operand1 = operand1 * operand2;
break;
case 4:
if (operand2.Magnitude == 0)
{
textBox1.Clear();
textBox2.Clear();
MessageBox.Show("Cannot divide by a number whose magnitude is zero");
operand1 = new Complex();
operand2 = new Complex();
listBox1.ClearSelected();
}
else
operand1 = operand1 / operand2;
break;
}
string s = operand1.ToString();
if (flag == 1)
{
string[] s1 = s.Split(' ');
if (s1[1] == "-")
{
textBox1.Text = s1[0];
textBox2.Text = "-" + s1[3];
}
else
{
textBox1.Text = s1[0];
textBox2.Text = s1[3];
}
}
else if (flag == 2)
{
string[] s1 = s.Split('#');
textBox1.Text = s1[0].Trim();
textBox2.Text = s1[1].Trim();
}
listBox1.Items.Add(operand1);
}
}
second code:
private void win_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Add)
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 1;
e.Handled = true;
}
else if (e.Key == Key.Subtract)
{
if (textBox2.Text == "")
{
e.Handled = false;
}
else
{
e.Handled = true;
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 2;
}
}
else if (e.Key == Key.Multiply)
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 3;
e.Handled = true;
}
else if (e.Key == Key.Divide)
{
operand1.Real = getOperand.Real;
operand1.Imag = getOperand.Imag;
flag1 = 4;
e.Handled = true;
}
else if (e.Key == Key.Enter)
{
e.Handled = true;
operand2.Real = getOperand.Real;
operand2.Imag = getOperand.Imag;
switch (flag1)
{
case 1:
operand1 = operand1 + operand2;
break;
case 2: operand1 = operand1 - operand2;
break;
case 3:
operand1 = operand1 * operand2;
break;
case 4:
if (operand2.Magnitude == 0)
{
textBox1.Clear();
textBox2.Clear();
MessageBox.Show("Cannot divide by a number whose magnitude is zero");
operand1 = new Complex();
operand2 = new Complex();
listBox1.UnselectAll();
}
else
operand1 = operand1 / operand2;
break;
}
string s = operand1.ToString();
if (flag == 1)
{
string[] s1 = s.Split(' ');
if (s1[1] == "-")
{
textBox1.Text = s1[0];
textBox2.Text = "-" + s1[3];
}
else
{
textBox1.Text = s1[0];
textBox2.Text = s1[3];
}
}
else if (flag == 2)
{
string[] s1 = s.Split('#');
textBox1.Text = s1[0].Trim();
textBox2.Text = s1[1].Trim();
}
listBox1.Items.Add(operand1);
}
}

It's very similar - but you compare e.Key to the Key enumeration.
Register your event handler somewhere (such as the constructor, or window_loaded):
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
}
And then in the event handler:
void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Subtract)
{
// Do something
}
}

You're looking for the TextInput event, or perhaps PreviewTextInput.
The EventArgs type is TextCompositionEventArgs; I believe you want the Text property here, but I'm not at all sure of that.

<TextBox x:Name="txtbx" KeyDown="OnKeyDownHandler" Height="23" Width="250">
</TextBox>
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
txtbx.Text = "You Entered: " + txtbx.Text;
}
}

Related

C# Calculator - Can't insert a number before a decimal point

I have implemented a calculator in C# everything apart from this is working fine, basically if I try to enter a number before a decimal point the number is reset and only then lets me enter numbers after the decimal point I'm assuming this is something stupid and will be a quick fix but I'm having no luck
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GrantCalculator
{
public partial class Form1 : Form
{
int count = 0;
float result = 0;
string operation = "";
bool operationPressed = false;
public Form1()
{
InitializeComponent();
}
private void btnClear_Click(object sender, EventArgs e)
{
//clearing result
txtResult.Text = "0";
result = 0;
}
private void btn_Click(object sender, EventArgs e)
{
if (count == 0)
{
//remove extra 0
if ((txtResult.Text == "0") || (operationPressed))
{
txtResult.Clear();
}
}
else if(count==1)
{
txtResult.Clear();
}
//event handler set for all number buttons which goto result textbox
operationPressed = false;
Button b = (Button)sender;
txtResult.Text += b.Text;
count = 0;
}
private void operator_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
operation = b.Text;
result = float.Parse(txtResult.Text);
operationPressed = true;
// count = 0;
}
private void btnEquals_Click(object sender, EventArgs e)
{
if (float.Parse(txtResult.Text) == 0 && operation == "/")
{
MessageBox.Show("You can't divide by 0");
}
//The math
switch (operation)
{
case "+":
txtResult.Text = (result + float.Parse(txtResult.Text)).ToString();
break;
case "-":
txtResult.Text = (result - float.Parse(txtResult.Text)).ToString();
break;
case "*":
txtResult.Text = (result * float.Parse(txtResult.Text)).ToString();
break;
case "/":
txtResult.Text = (result / float.Parse(txtResult.Text)).ToString();
break;
case "%":
txtResult.Text = (result % float.Parse(txtResult.Text)).ToString();
break;
default:
txtResult.Text = "Invalid";
break;
}
count++;
}
private void txtResult_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!Char.IsDigit(ch) && ch != 8 && ch != '.')
{
e.Handled = true;
}
// to allow only one decimal
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
private void btnPoint_Click(object sender, EventArgs e)
{
Button b = new Button();
string dot = txtResult.Text;
if (dot.Contains("."))
{
txtResult.Text = txtResult.Text + b.Text;
}
else
{
txtResult.Text = txtResult.Text = ".";
}
}
}
}
Thanks in advance :)
The line at the end:
txtResult.Text = txtResult.Text = ".";
The second = should be a +.
a = b = c = d = 5; notation is valid, and will set everything to 5.
As an addition to NibblyPig's answer:
Why are you creating a new Button and why are you adding the .Text of that button (which is string.Empty since it hasn't been set) to txtResult.Text when it already contains a dot?
Optimized version would be:
private void btnPoint_Click(object sender, EventArgs e)
{
if (!txtResult.Text.Contains("."))
{
txtResult.Text += ".";
}
}

Stopping the calculations because of predicted error

I am unsure how to ask this question as I can't quite well translate it.
I am currently working on my own Windows Form Application that will calculate the dimensions of a given package in inches (written all together in string format) and calculate the dimensions in centimeters, milimeters or even meters and at this point I was wondering what if someone entered wrong dimensions and given measures can not be parsed.
Something like Environment.Exit(), but without closing the application just stopping calculations and writing a message that an error has occured.
If there is a question like this answered, please do link it because I haven't been able to find it.
namespace PretvaranjeDimenzija
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public double mjera = 1;
public bool pogreska = false;
public string mjeraKratica = " cm";
public string dimenzijeIspis = "";
private void buttonIzracunaj_Click(object sender, EventArgs e)
{
string dim = textBoxDimenzije.Text;
if (dim.Contains('.'))
{
dim = dim.Replace('.', ',');
}
if (dim.Length != 0)
{
if (dim.IndexOf('x') != -1)
{
string[] multiDim = dim.Split('x');
double[] multiDimCentimetara = new double[multiDim.Length];
bool[] uspjeh = new bool[multiDim.Length];
for (int i = 0; i < multiDim.Length; i++)
{
uspjeh[i] = double.TryParse(multiDim[i], out multiDimCentimetara[i]);
if (uspjeh[i] == false)
{
pogreska = true;
goto kraj;
}
}
kraj:
if (pogreska == true)
{
MessageBox.Show("Doslo je do pogreske!");
pogreska = false;
}
else
{
double[] dimenzije = new double[multiDim.Length];
for (int i = 0; i < dimenzije.Length; i++)
{
dimenzije[i] = multiDimCentimetara[i] * 2.54 * mjera;
if (i == dimenzije.Length - 1)
{
dimenzijeIspis += dimenzije[i].ToString() + mjeraKratica;
}
else
{
dimenzijeIspis += dimenzije[i].ToString() + "x";
}
}
textBoxIspisDimenzija.Text = dimenzijeIspis;
dimenzijeIspis = "";
}
}
else
{
double dimCentimetara;
if(double.TryParse(dim, out dimCentimetara))
{
double dimenzija = dimCentimetara * 2.54 * mjera;
dimenzijeIspis = dimenzija.ToString() + mjeraKratica;
textBoxIspisDimenzija.Text = dimenzijeIspis;
dimenzijeIspis = "";
}
else
{
MessageBox.Show("Doslo je do pogreske!");
return;
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
mjera = 0.01;
mjeraKratica = " m";
if (radioButton2.Checked == true)
{
radioButton2.Checked = false;
radioButton1.Checked = true;
}
if (radioButton3.Checked == true)
{
radioButton3.Checked = false;
radioButton1.Checked = true;
}
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
mjera = 1;
mjeraKratica = " cm";
if (radioButton1.Checked == true)
{
radioButton1.Checked = false;
radioButton2.Checked = true;
}
if (radioButton3.Checked == true)
{
radioButton3.Checked = false;
radioButton2.Checked = true;
}
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
mjera = 10;
mjeraKratica = " mm";
if (radioButton2.Checked == true)
{
radioButton2.Checked = false;
radioButton3.Checked = true;
}
if (radioButton1.Checked == true)
{
radioButton1.Checked = false;
radioButton3.Checked = true;
}
}
}
It should be pretty simple, depending on your requirements. For example, you could just use a basic if block in your method.
void CalculateStuff()
{
// Get input. Do stuff.
if (IsInvalid)
{
MessageBox.Show("You did a bad thing.");
return; // exit the method.
}
// now that we know the input is good, do other stuff.
}
Substitute IsInvalid with whatever check condition you want that will return true if the input is not valid.

How to shorten if-else-if statement in c#

Can someone shorten this code?
There are 14 Buttons and 8 text Boxes. The action will be perform if the textbox is not empty and if it is not empty, then when you click it the button corresponding with the letter in the textbox will be visible again making the textbox empty.
private void txt1_Click(object sender, EventArgs e)
{
if (txt1.Text == "J")
{
txt1.Text = "";
btn1.Visible = true;
}
else if (txt1.Text == "M")
{
txt1.Text = "";
btn2.Visible = true;
}
else if (txt1.Text == "Y")
{
txt1.Text = "";
btn3.Visible = true;
}
else if (txt1.Text == "E")
{
if (btn4.Visible == true)
{
txt1.Text = "";
btn5.Visible = true;
}
else
{
txt1.Text = "";
btn4.Visible = true;
}
}
else if (txt1.Text == "Q")
{
txt1.Text = "";
btn6.Visible = true;
}
else if (txt1.Text == "L")
{
if (btn7.Visible == true)
{
txt1.Text = "";
btn10.Visible = true;
}
else
{
txt1.Text = "";
btn7.Visible = true;
}
}
else if (txt1.Text == "B")
{
txt1.Text = "";
btn8.Visible = true;
}
else if (txt1.Text == "C")
{
txt1.Text = "";
btn9.Visible = true;
}
else if (txt1.Text == "P")
{
txt1.Text = "";
btn11.Visible = true;
}
else if (txt1.Text == "I")
{
txt1.Text = "";
btn12.Visible = true;
}
else if (txt1.Text == "K")
{
txt1.Text = "";
btn13.Visible = true;
}
else if (txt1.Text == "O")
{
txt1.Text = "";
btn14.Visible = true;
}
}
Assuming all the btn variables are part of the state of your class then you can declare a method like so:
public Button Click(String txt) {
switch(txt) {
case "J":
return btn1;
case "M":
return btn2;
case "Y":
return btn3;
case "E":
return (btn4.Visible ? btn5 : btn4);
case "Q":
return btn6;
case "L":
return (btn7.Visible ? btn10 : btn7);
case "B":
return btn8;
case "C":
return btn9;
case "P":
return btn11;
case "I":
return btn12;
case "K":
return btn13;
case "O":
return btn14;
}
return null;
}
and then you call it:
var button = Click(txt1.Text);
if(button != null) {
button.Visible = true;
txt1.Text = "";
}
If however the btn variables have local scope, than instead of a method you can just define an inline Func<String,Button> delegate as so:
Func<String, Button> Click = txt => {
switch(txt) {
...
}
};
You'd still have to handle the special cases ("E" and "L") but you could use a Dictionary<string, Button> which would allow you to do a lookup:
var buttonDictionary = new Dictionary<string, Button>();
buttonDictionary["J"] = btn1;
buttonDictionary["M"] = btn2;
//etc...
if (buttonDictionary.Keys.Contains(txt1.Text))
{
txt1.Text = "";
buttonDictionary[txt1.Text].Visible = false;
}
That would reduce most of the repetitive code.
Looking at this: I'd suggest you go back think of more logical way to do whatever you're doing.
Out of my experience, any enormous chains of if-else in code represent that there has been a logical issue somewhere.
Also, familiarize yourself with switch statements

c# calculator minus not working properly

I've got to make a calculator for school, everything works except the minus button: 5-5 = -5 for example.
I know that the problem exists somewhere in my case "minus" but I just
can't get it figured out..
Here's the code.
Most of the variables are in dutch, I hope that won't be a problem!
Note: this problem exists when i do this: 5 - 5, so not using the equals button.
private int totaal = 0;
private Boolean lastClicked, equalsPressed, tussen = false;
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, EventArgs e)
{
switch(((Button)sender).Name){
case "one":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "1";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "1";
}
break;
case "two":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "2";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "2";
}
break;
case "three":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "3";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "3";
}
break;
case "four":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "4";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "4";
}
break;
case "five":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "5";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "5";
}
break;
case "six":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "6";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "6";
}
break;
case "seven":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "7";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "7";
}
break;
case "eight":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "8";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "8";
}
break;
case "nine":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "9";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "9";
}
break;
case "zero":
if (tussen)
{
uitkomstBox.Text = "";
tussen = false;
}
if (equalsPressed)
{
uitkomstBox.Text = uitkomstBox.Text + "0";
equalsPressed = false;
}
else
{
uitkomstBox.Text = uitkomstBox.Text + "0";
}
break;
case "plus":
totaal = totaal + Convert.ToInt32(uitkomstBox.Text);
uitkomstBox.Text = totaal.ToString();
tussen = true;
lastClicked = true;
break;
case "minus":
totaal = totaal - Convert.ToInt32(uitkomstBox.Text);
uitkomstBox.Text = totaal.ToString();
tussen = true;
lastClicked = false;
break;
case "clear":
uitkomstBox.Text = "";
totaal = 0;
break;
case "equals":
if (lastClicked)
{
uitkomstBox.Text = (totaal + Convert.ToInt32(uitkomstBox.Text)).ToString();
}
else
{
uitkomstBox.Text = (Convert.ToInt32(uitkomstBox.Text) - totaal).ToString();
}
equalsPressed = true;
totaal = 0;
break;
}
}
}
}
The problem is that you are subtracting the number twice. Once in the switch statement and then again here:
if (lastClicked)
{
uitkomstBox.Text = (totaal + Convert.ToInt32(uitkomstBox.Text)).ToString();
}
else
{
// You have already subtracted the number but then you are subtracting it again!
uitkomstBox.Text = (Convert.ToInt32(uitkomstBox.Text) - totaal).ToString();
}
It's the logic of the plus and minus buttons you need to check.
Take yourself through the code step by step.
In the beginning, totaal = 0 and uitkomnstBox.Text is empty. Then you click "5". So uitkomstBox.Text is "5". Then you click the "minus" button. totaal now changes to -5. i.e. before you have even entered a number to subtract from it. Then you click "5" again (to complete 5 - 5) but totaal doesn't change in this case until you click the equals button, at which point it hits that lastClicked logic which I don't really get... (I think it should end up as zero after that but you said the problem exists if you don't click "equals").
So it's not just that you're subtracting twice but you're subtracting before you even have a number to subtract.
As a possible solution, what I'd suggest is something like this: execute the logic of the operation ("plus" or "minus") after the next number is complete.
i.e. When someone clicks "minus" save this in memory somewhere until they have finished entering the next number, then subtract it from the total, or if they clicked "plus" add it. For the first number, process "plus" (e.g. 5 - 5 is processed as if it was entered as + 5 - 5)
private char operation = '+'; // Default first operation to "plus"
// Your other code...
// ...
// ...
case "plus" :
if (operation == '+') {
totaal += Convert.ToInt32(uitkomnstBox.Text);
}
if (operation == '-') {
totaal -= Convert.ToInt32(uitkomnstBox.Text);
}
operation = '+';
// anything else you want
break;
case "minus" :
if (operation == '+') {
totaal += Convert.ToInt32(uitkomnstBox.Text);
}
if (operation == '-') {
totaal -= Convert.ToInt32(uitkomnstBox.Text);
}
operation = '-';
// anything else you want
break;
case "equals" :
if (operation == '+') {
totaal += Convert.ToInt32(uitkomnstBox.Text);
}
if (operation == '-') {
totaal -= Convert.ToInt32(uitkomnstBox.Text);
}
operation = '+'; // Set back to default for next calculation
// anything else you want
break;
It looks like you are subtracting from totaal twice. Are you sure that adding works correctly? Check the code for your "=" button.
Also, maybe consider storing numbers for calculation in some counter int (or any other number type, if you are planning to allow fractions), rather than in textbox, since then you have to convert it back and forth just for the calculation.

Custom TextBox Control that Switches Keyboard Language Automatically c# WPF

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;
}
}
}

Categories

Resources