I am having another issue writing my chip8 Emu. I have managed to get all instructions working aside from those that require input or those that involve graphics.
I am trying to write a seperate class to simply determine whether a button is being pressed or not. I have been working on this for some time and I think that I must be missing something very simple or I do not understand something conceptually. Here is the class I am writing with the exact errors in the comments
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress() //Error 9 'WindowsFormsApplication1.userIn.checkPress()': not all code paths return a value C
{ //<---- it is teling me that a closing bracket is expected here?
private void key5_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyb_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key0_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keya_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keye_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key9_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key8_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key7_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyd_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyf_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key6_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key4_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyc_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key3_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key2_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key1_Click(object sender, EventArgs e)
{
pressed = true;
}
return pressed; //Error 6 Invalid token 'return' in class, struct, or interface member declaration
}
}
} // Error 8 Type or namespace definition, or end-of-file expected
Last line would not fit in the box
Does anyone have any Ideas or suggestions?
As always any help is appreciated!
} for checkPress method comes in end of class, your correct method:
public bool checkPress()
{
return pressed;
}
and your code should be like this:
using System;
...
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress() // This method
{
return pressed;
} // Must close here, not end of class
.
.
.
private void key1_Click(object sender, EventArgs e)
{
pressed = true;
}
}
}
If a button is belong to class XXX then you can expose its state by create a read-only property. It is not a good idea to create another class that depends on internal-implementation of XXX.
Short answer:
You have opened a method inside of another method.
Long answer
The following is your code properly indented (I recomend you AStyle for that):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress() //Error 9 'WindowsFormsApplication1.userIn.checkPress()': not all code paths return a value C
{ //<---- it is teling me that a closing bracket is expected here?
private void key5_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyb_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key0_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keya_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keye_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key9_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key8_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key7_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyd_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyf_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key6_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key4_Click(object sender, EventArgs e)
{
pressed = true;
}
private void keyc_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key3_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key2_Click(object sender, EventArgs e)
{
pressed = true;
}
private void key1_Click(object sender, EventArgs e)
{
pressed = true;
}
return pressed; //Error 6 Invalid token 'return' in class, struct, or interface member declaration
}
}
} // Error 8 Type or namespace definition, or end-of-file expected
Are you still unable to see the problem? Ok, here is a condensed version:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress() //Error 9 'WindowsFormsApplication1.userIn.checkPress()': not all code paths return a value C
{ //<---- it is teling me that a closing bracket is expected here?
private void key5_Click(object sender, EventArgs e)
{
pressed = true;
}
//And some other methods
return pressed; //Error 6 Invalid token 'return' in class, struct, or interface member declaration
}
}
} // Error 8 Type or namespace definition, or end-of-file expected
Does it look right to you?
Well, it just a way to put it, here is what the compiler sees:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress() //Error 9 'WindowsFormsApplication1.userIn.checkPress()': not all code paths return a value C
{ //<---- it is teling me that a closing bracket is expected here?
private void key5_Click(object sender, EventArgs e)
{
pressed = true;
}
//And some other methods
return pressed; //Error 6 Invalid token 'return' in class, struct, or interface member declaration
}
}
} // Error 8 Type or namespace definition, or end-of-file expected
Does it make sense now?
Chances are that you think the above code is right, if so this is not an answer... instead it is a question: What do you think you are trying to do?
Ok, yes, C# supports lambdas, are you trying to do the following?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress()
{
key5.Click += (sender, e) =>
{
pressed = true;
};
//And some other (anonymous) methods
return pressed;
}
}
}
But my instinct says that you just did some weird copy-paste and the intended code was like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication1
{
class userIn
{
bool pressed = false;
public userIn()
{
}
public bool checkPress()
{
return pressed;
}
private void key5_Click(object sender, EventArgs e)
{
pressed = true;
}
//And some other methods
}
}
Make sense? I hope.
Related
This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I am a newbie in C# and I have questions as below:
I have a Form1 name is setting Port Name, Baud Rate, Parity... of modbus protocol and I can open serial Port.
Also, I have another Form is called Form2, When Port is opened i want to close Form1 and Port alway Open => I can do it. But this problem that was I want to get data such as FC03 HolodingRegister, FC01 WriteSingleCoil... for Form2 but didnot.
I used delegate to transfer data from Form 1 to Form 2 but I could not use button Form2 to send FC01 signal.
How to use FC01, FC03,04... for Form2 when Form 1 connected.
Code Form1:
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;
using System.IO.Ports;
using Modbus.Device;
namespace ATS
{
public partial class frCommunication : Form
{
SerialPort serialPort = new SerialPort();
ModbusMaster Master;
public delegate void truyendulieu(string text);
public truyendulieu truyendata;
public delegate void truyendulieu1(string text1);
public truyendulieu1 truyendata1;
public delegate void truyendulieu2(string text2);
public truyendulieu2 truyendata2;
public frCommunication()
{
InitializeComponent();
}
private void frCommunication_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
cboxPort.Items.AddRange(ports);
cboxPort.SelectedIndex = 0;
}
private void btnConnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
try
{
serialPort.PortName = cboxPort.Text;
serialPort.BaudRate = Convert.ToInt32(cboxBaudRate.Text);
serialPort.DataBits = Convert.ToInt32(cboxDataBits.Text);
serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboxStopBits.Text);
serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboxParity.Text);
serialPort.Open();
Master = ModbusSerialMaster.CreateRtu(serialPort);
Master.Transport.Retries = 0; // don't have to to retries
Master.Transport.ReadTimeout = 300;//miliseconds
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (serialPort.IsOpen)
{
lblDisplay.Text = "Connected";
lblDisplay.ForeColor = System.Drawing.Color.Red;
cboxBaudRate.Enabled = false;
}
else
{
lblDisplay.Text = "Disconnected";
MessageBox.Show("Error!");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
try
{
serialPort.Close();
lblDisplay.Text = "Disconnected";
lblDisplay.ForeColor = System.Drawing.Color.Green;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
ushort[] holding_register = Master.ReadHoldingRegisters(1, 0, 10);
txtV_Grid.Text = Convert.ToString(holding_register[0]);
txtC_Grid.Text = Convert.ToString(holding_register[1]);
txtP_Grid.Text = Convert.ToString(holding_register[2]);
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (txtV_Grid.Text.Length > 0 || txtC_Grid.Text.Length > 0 || txtP_Grid.Text.Length > 0)
{
if (truyendata != null || truyendata1 != null)
{
truyendata(txtV_Grid.Text);
truyendata1(txtC_Grid.Text);
truyendata2(txtP_Grid.Text);
}
this.Hide();
}
}
private void txtV_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata != null)
{
truyendata(txtV_Grid.Text);
}
}
private void txtC_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata1 != null)
{
truyendata1(txtC_Grid.Text);
}
}
private void txtP_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata2 != null)
{
truyendata2(txtP_Grid.Text);
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void btnOn_ACB_Grid_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
DialogResult dl = MessageBox.Show("Would you like to turn On ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dl == DialogResult.Yes)
{
Master.WriteSingleCoil(1, 0, true);
}
else
{
Master.WriteSingleCoil(1, 0, false);
}
}
}
private void btnOff_ACB_Grid_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
DialogResult dl = MessageBox.Show("Would you like to turn Off ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dl == DialogResult.Yes)
{
Master.WriteSingleCoil(1, 0, false);
}
else
{
Master.WriteSingleCoil(1, 0, true);
}
}
}
}
}
Code Form2:
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;
using SymbolFactoryDotNet;
namespace ATS
{
public partial class frMain : Form
{
public frMain()
{
InitializeComponent();
}
private void communicationToolStripMenuItem_Click(object sender, EventArgs e)
{
frCommunication frm = new frCommunication();
frm.ShowDialog();
}
private void standardControl1_Load(object sender, EventArgs e)
{
}
private void LoadData(string data)
{
txtV.Text = "";
txtV.Text = data;
}
private void LoadData1(string data1)
{
txtC.Text = "";
txtC.Text = data1;
}
private void LoadData2(string data2)
{
txtP.Text = "";
txtP.Text = data2;
}
private void btnConnect_Click(object sender, EventArgs e)
{
frCommunication frm = new frCommunication();
frm.truyendata = new frCommunication.truyendulieu(LoadData);
frm.truyendata1 = new frCommunication.truyendulieu1(LoadData1);
frm.truyendata2 = new frCommunication.truyendulieu2(LoadData2);
frm.ShowDialog();
}
private void txtV_TextChanged(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
if(picOn.Visible == false)
{
picOn.Visible = true;
picOff_Grid.Visible = false;
// standardControl3.DiscreteValue2 = true;
}
else
{
picOn.Visible = false;
picOff_Grid.Visible = true;
}
}
private void frMain_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("HH:mm:ss dd-MM-yyyy");
}
private void btnOn_Grid_Click(object sender, EventArgs e)
{
}
}
}
When I understand you right, you will in Form1 open a connection, close the Form, open a new Form2 and use this connection there?
Well, when that's the case, you could make an special Connection Singleton to hold this connection then you can use it in your Form2
using System;
namespace Sandbox
{
public sealed class Connection
{
private static readonly Lazy<Connection> _instance = new Lazy<Connection>(() => new Connection());
public static Connection Instance => _instance.Value;
private Connection()
{ }
// Implement your Connection Code here.
}
}
I have a form Modal ShowDialog. Trying the close the Form created if one of two things happen 1 button on the form is pushed or 2 a value changes in a static variable.So far the button works I can use another button to check the status of the value and view the change? How can I have the 2nd part close the form?
Main_Menu.cs
public void OverloadTripearly()
{
OverloadTripEarly overloadTripEarly = new OverloadTripEarly();
overloadTripEarly.Owner = this;
overloadTripEarly.ShowDialog();
// overloadTripEarly.Refresh();
// OLTrip = overloadTripEarly; // assign object to enter
}
OverloadTripEarly.cs 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;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormTitlepageNew
{
public partial class OverloadTripEarly : Form
{
public OverloadTripEarly()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
else
{
this.Close(); // close if button is pressed
this.Dispose();
}
}
private void OverloadTripEarly_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
do
{
Thread.Sleep(100);
GlobalVariables.OverloadTest = NIDMMPXIeSlot5ConsoleApplication.SingleResistance
MeasurementApp();
if (double.IsNaN(GlobalVariables.OverloadTest))
{
GlobalVariables.OverloadFlag = true;
this.Close();
e.Cancel = true;
}
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
this.Close();
return;
}
} while (double.IsNaN(GlobalVariables.OverloadTest));
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{ this.Close();
this.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
GlobalVariables.OverloadTest = NIDMMPXIeSlot5ConsoleApplication.SingleResistance
MeasurementApp();
if (double.IsNaN(GlobalVariables.OverloadTest))
{
textBox1.Text = "NaN".ToString();
}
else
{ textBox1.Text = GlobalVariables.OverloadTest.ToString(); }
}
}
}
i think your Problem is, that you change the 'Win Form' from another thread.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{ this.Close();
this.Dispose();
}
}
Backgroundworker is calling from another thread. So you have to check if InvokeIsRequired and if so then invoke the this.Close()
check this link
This question already has answers here:
How do you pass an object from form1 to form2 and back to form1?
(4 answers)
Closed 5 years ago.
I'm supposed to make a math practice program for kids. They should be able to choose 1 operation and the amount of digits (1, 2 or 3 digit) 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.
I have two selections being made on form1, operations and # of digits, which are assigned numbers (1. (*) 2. (/) 3. (+) 4. (-)). All i need to do is communicate the operation number and # of digits to form2, where the questions will be generated and displayed.
Here's my code for form1 so far:
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 FinalProject
{
public partial class Form1 : Form
{
public static int operation = 0;
public static int digits = 0;
public Form1()
{
InitializeComponent();
}
// this is to make sure only one box is checked for both selections. Starts here
private void label1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
private void MulCB_CheckedChanged(object sender, EventArgs e)
{
if ( MulCB.Checked == true)
{
operation = 1;
DivCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void DivCB_CheckedChanged(object sender, EventArgs e)
{
if (DivCB.Checked == true)
{
operation = 2;
MulCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void AddCB_CheckedChanged(object sender, EventArgs e)
{
if (AddCB.Checked == true)
{
operation = 3;
DivCB.Checked = false;
SubCB.Checked = false;
MulCB.Checked = false;
}
}
private void SubCB_CheckedChanged(object sender, EventArgs e)
{
if (SubCB.Checked == true)
{
operation = 4;
DivCB.Checked = false;
AddCB.Checked = false;
MulCB.Checked = false;
}
}
private void oneDCB_CheckedChanged(object sender, EventArgs e)
{
if(oneDCB.Checked == true)
{
digits = 1;
twoDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void twoDCB_CheckedChanged(object sender, EventArgs e)
{
if ( twoDCB.Checked == true)
{
digits = 2;
oneDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void threeDCB_CheckedChanged(object sender, EventArgs e)
{
if (threeDCB.Checked == true)
{
digits = 3;
oneDCB.Checked = false;
twoDCB.Checked = false;
}
}
private void button8_Click(object sender, EventArgs e)
{
// operations: 1. (*) 2. (/) 3. (+) 4. (-)
// digits are as number indicates.
// Second window popup.
Form2 settingsForm = new Form2();
settingsForm.Show();
}
}
}
Here's form2, naked pretty much.
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 FinalProject
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void FinishedBtn_Click(object sender, EventArgs e)
{
}
}
}
This might work.
There are comments in the code.
The workflow is creating a new instance of the class Form2 and setting two public variables. Public means that they can be accessed from outside of the class (see here, if you want). Then the method Show() is called and the Form appears. In the Form2 code, the public variables now have the values previously specified and can be used.
Form1:
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 FinalProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// this is to make sure only one box is checked for both selections. Starts here
private void label1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
private void MulCB_CheckedChanged(object sender, EventArgs e)
{
if ( MulCB.Checked == true)
{
operation = 1;
DivCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void DivCB_CheckedChanged(object sender, EventArgs e)
{
if (DivCB.Checked == true)
{
operation = 2;
MulCB.Checked = false;
AddCB.Checked = false;
SubCB.Checked = false;
}
}
private void AddCB_CheckedChanged(object sender, EventArgs e)
{
if (AddCB.Checked == true)
{
operation = 3;
DivCB.Checked = false;
SubCB.Checked = false;
MulCB.Checked = false;
}
}
private void SubCB_CheckedChanged(object sender, EventArgs e)
{
if (SubCB.Checked == true)
{
operation = 4;
DivCB.Checked = false;
AddCB.Checked = false;
MulCB.Checked = false;
}
}
private void oneDCB_CheckedChanged(object sender, EventArgs e)
{
if(oneDCB.Checked == true)
{
digits = 1;
twoDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void twoDCB_CheckedChanged(object sender, EventArgs e)
{
if ( twoDCB.Checked == true)
{
digits = 2;
oneDCB.Checked = false;
threeDCB.Checked = false;
}
}
private void threeDCB_CheckedChanged(object sender, EventArgs e)
{
if (threeDCB.Checked == true)
{
digits = 3;
oneDCB.Checked = false;
twoDCB.Checked = false;
}
}
private void button8_Click(object sender, EventArgs e)
{
// operations: 1. (*) 2. (/) 3. (+) 4. (-)
// digits are as number indicates.
// Second window popup.
// it's the question form, right?
Form2 questionForm = new Form2();
//"Write" your settings in the other form's variables
//You will have to write code that finds out which checkbox is which number! For now its fixed.
questionForm.operation = 2;
questionForm.digits = 1;
questionForm.Show();
//Hide Form1
this.Hide();
}
}
}
Form2:
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 FinalProject
{
public partial class Form2 : Form
{
public static int operation;
public static int digits;
public Form2()
{
InitializeComponent();
}
//do NOT paste this. It can be added by creating an event handler
// you also might not need this, but this method is called when this Form appears. It's an example.
// https://msdn.microsoft.com/en-us/library/zwwsdtbk(v=vs.80).aspx
private void Form2_Load(object sender, EventArgs e)
{
//here you can use your variables for example (also anywhere within this class!)
//e.g.
Textbox1.Text = (string)operation;
}
private void FinishedBtn_Click(object sender, EventArgs e)
{
}
}
}
I've been making a game called dog simulator. Im at the point on where the movement needs to be developed, however, for some reason, the function didn't activate. Visual Studio (the IDE I use) said there were no errors. Some help will be appreciated
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 dog_simulator
{
public partial class Form1 : Form
{
bool right;
bool left;
public int left_var = 5;
public int right_var = 5;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
public void button2_Click(object sender, EventArgs e)
{
panel1.Visible = false;
}
public void button1_Click(object sender, EventArgs e)
{
panel1.Visible = false;
}
public void Form1_KeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine("Left has been pressed");
if (e.KeyCode == Keys.Left)
{
left = true;
Console.WriteLine("Left has been pressed");
}
if(e.KeyCode == Keys.Right)
{
right = true;
Console.WriteLine("Right has been pressed");
}
}
public void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
left = false;
Console.WriteLine("Left has been let go of");
}
if (e.KeyCode == Keys.Right)
{
right = false;
Console.WriteLine("Right has been let go of");
}
}
public void timer1_Tick(object sender, EventArgs e)
{
if (right == true)
{
player.Left += left_var;
}
if (left == true)
{
player.Left -= left_var;
}
Invalidate();
}
private void dog_Click(object sender, EventArgs e)
{
}
private void player_Click(object sender, EventArgs e)
{
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
}
}
}
For a Windows Form to be able to see the key pressed you need to set the
this.KeyPreview = true;
in designer or in form code. Otherwise the key presses will be received by the control that has the current focus.
MSDN: Form.KeyPreview
I am building a vending machine and I am stuck on adding coins.
Coin should automatically be calculated when I click on the assigned button But Instead I am just getting the value inside textbox here's the 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 VendingMachine
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void operator_Click(object sender, EventArgs e)
{
new Form2().Show();
this.Hide();
}
private void fiveP_Click(object sender, EventArgs e)
{
balance.Text = ((double)balance.Text + 0.05).ToString();
}
private void tenP_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "0.10";
}
private void twentyP_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "0.20";
}
private void fiftyP_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "0.50";
}
private void onePound_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "1.00";
}
private void twoPound_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "2.00";
}
}
}
Coin Class
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace VendingMachine
{
[Serializable]
internal class Coin : ISerializable, IComparable
{
public string coinName = "";
public double coinValue = 0.0;
public int coinBalance = 0;
public string Name
{
get { return this.coinName; }
set { this.coinName = value; }
}
public double Value
{
get { return this.coinValue; }
set { this.coinValue = value; }
}
public int Balance
{
get { return this.coinBalance; }
set { this.coinBalance = value; }
}
public Coin(string coin_name)
{ this.coinName = coin_name; }
public Coin(SerializationInfo info, StreamingContext ctxt)
{
this.coinValue = (double)info.GetValue("CoinValue", typeof(double));
this.coinName = (string)info.GetValue("CoinName", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("CoinValue", this.coinValue);
info.AddValue("CoinName", (object)this.coinName);
}
public int CompareTo(object obj)
{
if (obj is Coin)
return this.Value.CompareTo(((Coin)obj).Value);
else
throw new ArgumentException("object is not a Coin");
}
public static IComparer sortByCoinName()
{
return (IComparer)new Coin.sortByCoinNameHelper();
}
private class sortByCoinNameHelper : IComparer
{
int IComparer.Compare(object a, object b)
{
return ((Coin)a).Name.CompareTo(((Coin)b).Name);
}
}
}
}
if balance is the textbox you are working with, you are clearing it with the button press, erasing whatever was in it prior to the button press, so it will always be "" + whatever. also, you can't add strings like that, "1.00" + "2.00" == "1.002.00", != "3.00"
You are adding strings rather than numbers. You'll need to convert your strings into numbers to add them together, and you shouldn't clear your results first.
For example:
private void fiveP_Click(object sender, EventArgs e)
{
// balance.Clear(); <- You don't need this.
balance.Text = ((double)balance.Text + 0.05).ToString();
}
that is because you are using a string type for calculating.. there is a difference between calculating something and displaying it. in short:
float value = 0;
void print()
{
balance.Text = string.Format("{0:0.00}", value);
}
private void fiveP_Click(object sender, EventArgs e)
{
value += 0.05f;
print();
}
private void tenP_Click(object sender, EventArgs e)
{
value += 0.10f;
print();
}
private void twentyP_Click(object sender, EventArgs e)
{
value += 0.20f;
print();
}
private void fiftyP_Click(object sender, EventArgs e)
{
value += 0.50f;
print();
}
private void onePound_Click(object sender, EventArgs e)
{
value += 1;
print();
}
private void twoPound_Click(object sender, EventArgs e)
{
value += 2;
print();
}
in your code you are not adding numbers, example:
you have this code:
private void tenP_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "0.10";
}
the value of balance.Text = "0.10"
then, if the next code is executed:
private void fiftyP_Click(object sender, EventArgs e)
{
balance.Clear();
balance.Text = balance.Text + "0.50";
}
the value of balance.Text = "0.50"
the point is that your are trying to add strings not numbers and you are clearing your previous value