This question already has answers here:
Best way to implement keyboard shortcuts in a Windows Forms application?
(9 answers)
Closed 6 years ago.
i have a point of sale program made with C#
when pressing submit button it submit the sale and print the invoice
i want to make a shortcut for it so when i press a shortcut key on the keyboard
it does the buttons work
here is my button Code:
private void btnCompleteSalesAndPrint_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Do you want to Complete Sale and Print?\n\n -If you need any item [duplicate] (1 item 2 piece) \n -Please Increase item Quantity \n ----- by clicking + sign ", "Yes or No", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (result == DialogResult.Yes)
{
if (txtPaidAmount.Text == "")
{
MessageBox.Show("Sorry ! you have not enough product \n Please Purchase product or Increase Product Quantity");
// detail_info go = new detail_info();
// go.ShowDialog();
}
else
{
try
{
sales_item();
//Save payment info into sales_payment table
payment_item();
// 5 % Rewards Point add to customer Account for total Payable amount
AddCredit();
PrintPage mkc = new PrintPage();
mkc.saleno = txtInvoice.Text;
mkc.vat = txtVATRate.Text;
mkc.dis = txtDiscountRate.Text;
mkc.paidamt = txtPaidAmount.Text;
mkc.subtotal = lblsubtotal.Text;
mkc.ShowDialog();
showincrement();
ClearForm2();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
}
}
How about using the KeyDown event on the form? Say for example that the shortcut key is "E".
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.E)
{
btnCompleteSalesAndPrint_Click(sender, new EventArgs());
}
}
However this wouldn't really work with multiple keys, so instead you may want to use a system that allows you to check if a certain key is pressed instead. Say that "CTRL" + "E" is the shortcut. Use the "PresentationCore" library in order to access the "System.Windows.Input" namespace.
using System.Windows.Input;
//[...]
private bool ControlPressed//Returns true if the left control button or the right control button is pressed. Returns false if neither are pressed.
{
get
{
return Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);
}
}
private bool E_Pressed//Boolean that returns true if "E" is pressed and false if it isn't.
{
get
{
return Keyboard.IsKeyDown(Key.E);
}
}
And to check at regular intervals to see if these keys are pressed.
public Form1()
{
InitializeComponent();
Timer timer = new Timer();//Create new instance of Timer.
timer.Interval = 1;
timer.Tick += new EventHandler(timer_Tick);//Set an eventhandler to occur after each 1000th of a second.
timer.Enabled = true;
}
private void timer_Tick(object sender, EventArgs e)
{
if (ControlPressed && E_Pressed)
{
btnCompleteSalesAndPrint_Click(sender, new EventArgs());
}
}
Codf bflow:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Input;
namespace hmmmhmh
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Timer timer = new Timer();
timer.Interval = 1;
timer.Tick += new EventHandler(timer_Tick);
timer.Enabled = true;
}
private void timer_Tick(object sender, EventArgs e)
{
if (Control_Pressed && F_Pressed)
{
button1_Click(sender, e);
}
}
private bool Control_Pressed
{
get
{
return Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);
}
}
private bool F_Pressed
{
get
{
return Keyboard.IsKeyDown(Key.E);
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("hlhlh");
}
}
}
Related
We're doing C# this week. It's the Lunch Order assignment, and the groupBox for my Add-ons menu does not populate until I check another main course. The Add-ons are all Checkboxes inside the groupBox.
I thought I would overcome this by setting the first main course item (hamburger) as checked by default. Did not fix it, and so I thought maybe I should have one of the add-on menu check-boxes checked by default... This also did not improve anything.
This is what it looks like when I run the app:
LunchOrderLaunch No add-ons
And when I check another main course option:
LunchOrderMainCourseChange Add-ons show
Here's the code (yes things are out of order because I am new to this and trying to work around things. Apologies for that in advance:
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 LunchAppLAB1_V2
{
public partial class frmLunchOrder : Form
{
// Global declaration
decimal Subtotal;
decimal Tax = 0.05m;
decimal OrderTotal;
public frmLunchOrder()
{
InitializeComponent();
}
private void grbxAddOns_CheckChanged(object sender, EventArgs e)
{
}
private void btnExit_Click(object sender, EventArgs e)
{
string message = "Hey! Thanks for dining with us today!\n Will you be coming
back?";
DialogResult button =
MessageBox.Show(message, "Dear Customer",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (button == DialogResult.No)
{
this.Close();
}
if (button == DialogResult.Yes)
{
MessageBox.Show("Hey! Thanks dude! Hope to see you soon!", "Greeting
Message");
this.Close();
}
}
private void btnPlaceOrder_Click(object sender, EventArgs e)
{
decimal add = 0m;
if (chkbx1.Checked)
{
add++;
}
if (chkbx2.Checked)
{
add++;
}
if (chkbx3.Checked)
{
add++;
}
if (rdoHamburger.Checked)
{
decimal Hamburger = Convert.ToDecimal(rdoHamburger.Checked);
Hamburger = 6.95m;
Subtotal = Hamburger + (add * .75m);
Tax = Subtotal * 0.05m;
OrderTotal = Tax + Subtotal;
txtSubtotal.Text = Subtotal.ToString("c");
txtTax.Text = Tax.ToString("c");
txtOrderTotal.Text = OrderTotal.ToString("c");
}
else if (rdoPizza.Checked)
{
decimal Pizza = Convert.ToDecimal(rdoPizza.Checked);
Pizza = 5.95m;
Subtotal = Pizza + (add * .50m);
Tax = Subtotal * 0.05m;
OrderTotal = Tax + Subtotal;
txtSubtotal.Text = Subtotal.ToString("c");
txtTax.Text = Tax.ToString("c");
txtOrderTotal.Text = OrderTotal.ToString("c");
}
else if (rdoSalad.Checked)
{
decimal Salad = Convert.ToDecimal(rdoSalad.Checked);
Salad = 4.95m;
Subtotal = Salad + (add * .25m);
Tax = Subtotal * 0.05m;
OrderTotal = Tax + Subtotal;
txtSubtotal.Text = Subtotal.ToString("c");
txtTax.Text = Tax.ToString("c");
txtOrderTotal.Text = OrderTotal.ToString("c");
}
}
private void rdoHamburger_CheckedChanged(object sender, EventArgs e)
{
grbxAddOns.Text = "Add-on items($.75/each)";
chkbx1.Text = "Lettuce, Tomato, and Onions";
chkbx2.Text = "Ketchup, Mustard, and Mayonnaise";
chkbx3.Text = "French Fries";
}
private void rdoPizza_CheckedChanged(object sender, EventArgs e)
{
grbxAddOns.Text = "Add-on items($.50/each)";
chkbx1.Text = "Pepperoni";
chkbx2.Text = "Sausage";
chkbx3.Text = "Olives";
}
private void rdoSalad_CheckedChanged(object sender, EventArgs e)
{
grbxAddOns.Text = "Add-on items($.25/each)";
chkbx1.Text = "Croutons";
chkbx2.Text = "Bacon Bits";
chkbx3.Text = "Bread Sticks";
}
private void btnReset_Click(object sender, EventArgs e)
{
RecursiveClearTextBoxes(this.Controls);
}
private void RecursiveClearTextBoxes(Control.ControlCollection cc)
{
foreach (Control ctrl in cc)
{
TextBox tb = ctrl as TextBox;
if (tb != null)
tb.Clear();
else
RecursiveClearTextBoxes(ctrl.Controls);
}
}
}
}
All of the radio buttons for the main course option have been coded with a CheckedChanged instruction. So I understand that they don't fire until the button is physically checked (and the checked button changes) So I am wondering how to do this and have the add-ons populate to begin with. I've been trying to find a solution since yesterday, and now I'm pretty much out of time. I'm a C# noob with this assignment due tomorrow...
In the constructor, add this line after InitializeComponent();
public frmLunchOrder()
{
InitializeComponent();
rdoHamburger_CheckedChanged(null, null); // <-- this line
}
Your problem is that, even though you're setting one to be clicked by default, it's still not firing the event that sets the check box text.
So you can just call this event manually in the constructor.
I am new to the C# scene, so don't really have much knowledge - This is my first project.
I am looking to create a very basic calorie counter, which eventually will include other functions.
Here's what I have so far;
I want to know how to take the value from the text box on the click of the 'Add' button - Which adds to the total value (bottom right)
I'm looking for any tips/videos to help so anything is appreciated.
TIA
I made a simple implementation for you, you could refer to it:
using System;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
bool Flag = Int32.TryParse(textBox1.Text, out int result);//Determine if it is a number
if (textBox1.Text == "")//If it is null, falg takes true and skips the next judgment
{ Flag = true; }
else if (!Flag)
{
MessageBox.Show("Input Error");
textBox1.Text = null;
}
}
private void button1_Click(object sender, EventArgs e)
{
Int32.TryParse(textBox1.Text, out int result);
int total =result + Convert.ToInt32(label3.Text);
label3.Text = total.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
label3.Text = "0";
}
}
}
I'm new to C# and I need this function for a program im working on for school. I need to make a new window pop up when i click a button, not a message box though like a forms window, one that i can design with text boxes and buttons. What is on the new pop up window depends on the previous window but i can figure that out.
Also I need a way to close the previous window once the new one appears
Here's my code:`
// This makes sure only one box is checked
private void MulCB_CheckedChanged(object sender, EventArgs e)
{
if( MulCB.Checked == true)
{
DivCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void DivCB_CheckedChanged(object sender, EventArgs e)
{
if (DivCB.Checked == true)
{
MulCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void AddCB_CheckedChanged(object sender, EventArgs e)
{
if (AddCB.Checked == true)
{
DivCB.Checked = false;
SubCB.Checked = false;
MulCB.Checked = false;
}
}
private void SubCB_CheckedChanged(object sender, EventArgs e)
{
if (SubCB.Checked == true)
{
DivCB.Checked = false;
AddCB.Checked = false;
MulCB.Checked = false;
}
}
private void oneDCB_CheckedChanged(object sender, EventArgs e)
{
if(oneDCB.Checked == true)
{
twoDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void twoDCB_CheckedChanged(object sender, EventArgs e)
{
if ( twoDCB.Checked == true)
{
oneDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void threeDCB_CheckedChanged(object sender, EventArgs e)
{
if (threeDCB.Checked == true)
{
oneDCB.Checked = false;
twoDCB.Checked = false;
}
}
// ends here
// Button operation
private void button8_Click(object sender, EventArgs e)
{
var form = new Form();
}
}
}
`
Thanks a lot!
Sal
The project is im supposed to make a quizzing program for kids. They should be able to choose 1 operation and the amount of digits the numbers will have. It then has to out put 10 random questions according to the selection made by the kid, then once they have completed the quiz, it should display their results and which questions they got wrong.
Assuming that the design of the window doesn't have to be completely dynamic, you can design it in Visual Studio (I'm assuming you did so with the first one). Then you can pass the results to the window. Like:
// Note: Form2 ist the name of your designed From
Form2 myform = new Form2();
this.Hide();
//You could pass the question settings like this
// 1 is for multiplication, 2 for division,3 for addition, 4 for substraction
myform.operation=1;
myform.digits=2
myform.Show();
And in the code of Form2:
namespace Yournamespace {
public partial class Form2: Form {
//Add these two lines about here
public static int operation;
public static int digits;
public Form2() {
InitializeComponent();
}
}
}
Then you can use the variables in Form2 and fill in the textbox or other elements you might design.
Also: You cloud use radio buttons instead of checkboxes as you then won't have you worry about unchecking the other checkboxes.
Here's the problem:
I'm using a MaskedTextBox for phones masks. But, the Mask must accept two kinds of mask, like, the default mask is like this (00) 0000-0000, but sometimes the mask need to have one more slot, like this (00) 0000-00000.
This process must be dynamic. If the user type more than 10 chars, the MaskedTextBox will change his own mask.
Some time ago, I made it using VB.Net, but now, I need to do this using C#.
Here's just a example using VB.NET that I made some time ago.
Private Sub MaskedTextValidacao_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles Me.Validating
Me.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals
If Me.Text.Contains(" ") Or Me.Text.EndsWith(" ") Or Me.Text.StartsWith(" ") Then
Me.Text.Replace(" ", "")
End If
If Me.Text.Count.Equals(10) Or Me.MaskCompleted.Equals(True) Then
Me.BackColor = Color.LightGreen
Me.Text = Me.Text.TrimEnd
ElseIf Me.Text = "" Then
Me.BackColor = Color.White
Else
Me.BackColor = Color.LightCyan
End If
End Sub
Now, I'm trying to make something better and using C#.
Can someone help me? I mean, just give me a light, because I'm stuck!
You can make it like this :
public class CustomMaskedBox : MaskedTextBox
{
public CustomMaskedBox()
{
this.MaskInputRejected += CustomMaskedBox_MaskInputRejected;
this.Enter += CustomMaskedBox_Enter;
this.Leave += CustomMaskedBox_Leave;
}
void CustomMaskedBox_Leave(object sender, EventArgs e)
{
if (this.MaskFull)
{
this.BackColor = Color.LightGreen;
}
else
{
this.Mask = "(00) 0000-0000";
this.BackColor = Color.LightGreen;
}
if (!this.MaskCompleted)
{
this.BackColor = Color.LightCoral;
}
}
void CustomMaskedBox_Enter(object sender, EventArgs e)
{
this.BackColor = Color.LightBlue;
}
void CustomMaskedBox_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
if (this.MaskFull)
{
this.Mask = "(00) 0000-00000";
this.BackColor = Color.LightYellow;
}
}
}
You are looking for this I think( where maskedTextBox1 is control on form): So when the form starts it defaults to the Mask of
this.maskedTextBox1.Mask = "(00) 0000-0000";
When the user enters the values and the Mask is full then you can change the mask again:
private void maskedTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (this.maskedTextBox1.MaskFull)
{
this.maskedTextBox1.Mask = "(00) 0000-00000";
}
}
You can customise the key press/key down events to pick up the values dynamically.
thanks for the answers. I tried something and it's working.
It's use colors to identify if the field are Right or not. It also modify the mask.
Most part of it are in the Leave Event.
Think:
User type a number with 10 digits (00) 0000-0000
User leave the field
Then, the User enter again in the field and add a new digit (00)
0000-00000
User leave the field
Again, the user enter in the field and remove some digit (00)
0000-0000
The EVENT LEAVE can handle with this. I just like to know how can I do it in a "Professional Way",
I mean, this MaskedTextBox will be a part of a Class with others Custom Controls, so...there's a better way to do something like I did?
Here's the code that I made, and again, thanks guys!!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MaskedTextBox
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
if (maskedTextBox1.MaskFull)
{
maskedTextBox1.Mask = "(00) 0000-00000";
maskedTextBox1.BackColor = Color.LightYellow;
}
}
private void maskedTextBox1_Enter(object sender, EventArgs e)
{
maskedTextBox1.BackColor = Color.LightBlue;
}
private void maskedTextBox1_Leave(object sender, EventArgs e)
{
if (maskedTextBox1.MaskFull)
{
maskedTextBox1.BackColor = Color.LightGreen;
}
else
{
maskedTextBox1.Mask = "(00) 0000-0000";
maskedTextBox1.BackColor = Color.LightGreen;
}
if (!maskedTextBox1.MaskCompleted)
{
maskedTextBox1.BackColor = Color.LightCoral;
}
}
}
}
Hey guys im trying to get a simple button masher up, What i want timer1 to do is mash keys in richtextbox1 for 30 seconds over and over, after 30 seconds Activate timer2, which will disable timer 1 and press keys in richtextbox 2 once, then wait 10 seconds and activate timer 1 again.
Im extremley new to c# but ive tried using timer 3 to stop timer 2 and start timer 1 again and it just messes it self up. The code ive tried is below. Any help apreciated...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
SendKeys.Send(richTextBox1.Text);
SendKeys.Send("{ENTER}");
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer2.Enabled = true;
}
private void timer2_Tick(object sender, EventArgs e)
{
SendKeys.Send(richTextBox2.Text);
SendKeys.Send("{ENTER}");
timer1.Enabled = false;
}
private void timer3_Tick(object sender, EventArgs e)
{
timer1.Enabled = true;
timer2.Enabled = false;
}
private void richTextBox2_TextChanged(object sender, EventArgs e)
{
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
I suggest to use just one timer, increment a state counter every second, and perform an action base on the current state.
public Form1()
{
this.InitializeComponent();
// Just to illustrate - can be done in the designer.
this.timer.Interval = 1000; // One second.
this.timer.Enable = true;
}
private Int32 state = 0;
private void timer_Tick(Object sender, EventArgs e)
{
if ((0 <= this.state) && (this.state < 30)) // Hit text box 1 30 times.
{
SendKeys.Send(this.richTextBox1.Text);
SendKeys.Send("{ENTER}");
}
else if (this.state == 30) // Hit text box 2 once.
{
SendKeys.Send(this.richTextBox2.Text);
SendKeys.Send("{ENTER}");
}
else if ((31 <= this.state) && (this.state < 40)) // Do nothing 9 times.
{
// Do nothing.
}
else
{
throw new InvalidOperationException(); // Unexpected state.
}
// Update state.
this.state = (this.state + 1) % 40;
}
The variant with two numeric up down controls.
public Form1()
{
this.InitializeComponent();
// Just to illustrate - can be done in the designer.
this.timer.Interval = 1000; // One second.
this.timer.Enable = true;
}
private Int32 state = 0;
private void timer_Tick(Object sender, EventArgs e)
{
Decimal n1 = this.numericUpDown1.Value;
Decimal n2 = this.numericUpDown2.Value;
if ((0 <= this.state) && (this.state < n1))
{
SendKeys.Send(this.richTextBox1.Text);
SendKeys.Send("{ENTER}");
}
else if (this.state == n1)
{
SendKeys.Send(this.richTextBox2.Text);
SendKeys.Send("{ENTER}");
}
else if ((n1 <= this.state) && (this.state < n1 + n2))
{
// Do nothing.
}
else
{
// Reset state to resolve race conditions.
this.state = 0;
}
// Update state.
this.state = (this.state + 1) % (n1 + n2);
}
If timer3 is running continuously, won't it start timer1 and stop timer2 at unpredictable times, without warning?
IOW, what starts and stops timer3?
As JustLoren pointed out, there might be a cleaner way to do this. Perhaps a single timer event and some controlling logic and flags, rather than trying to juggle three timers.