what i am attempting to do is, get user input from a text box, convert it to an int and then use that. i got everything to work except the the try and catch. incase the person puts a letter instead of a number. with the code below it always catches something. i have no idea what is catches something. i've taken out the bool test and if i put in a letter it will just throw the exception then go to the beeping. other then waiting for a valid input.
please excuse my messy code, i am still a beginner c# programmer :D thanks in advanced!
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 WindowsFormsApplication4
{
public partial class Form1 : Form
{
bool tone = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bool test = true;
speedInput.Clear();
beep.Clear();
int beepspeed = 90;
int speed = 100;
string speedtext = this.speedInput.Text;
string beeptext = this.beep.Text;
try
{
test = true;
beepspeed = Convert.ToInt32(beeptext);
speed = Convert.ToInt32(speedtext);
}
catch (Exception)
{
MessageBox.Show("numbers above 37 only!!");
test = false;
}
if (test)
{
for (int i = 0; i < beepspeed; i++)
{
if (this.tone)
{
Random ran = new Random();
int rand = ran.Next(400, 3000);
Console.Beep(rand, speed);
}
else
{
Console.Beep(1000, speed);
}
}
}
}
private void radioButtonYes_CheckedChanged(object sender, EventArgs e)
{
this.tone = true;
}
private void radioButtonNo_CheckedChanged(object sender, EventArgs e)
{
this.tone = false;
}
}
}
You are cleaning the content of the inputs at the beginning of the button1_click
speedInput.Clear();
beep.Clear();
Then when you try to convert empty string to int32 it fails
beepspeed = Convert.ToInt32(beeptext);
speed = Convert.ToInt32(speedtext);
Related
I am very new to all of this, so bear with me.
I am trying to create a makeshift vr headset where I send accelerometer values over Bluetooth using the serial port. These values will them be separated and plugged into the SetCursorPos function with a for loop with delays so it moves smoothly and doesn't give me motion sickness. Figured some background on what it is will help with the actual question.
The port.readline I am using returns a string, so I tried to do int potValue = Int32.Parse(port.readline());. However it says input string was not in correct format. I googled everywhere, tried int potValue = Convert.Int32(port.readline()); with no luck either. So first question is how do I even send an int value sent from an arduino to my computer so I can plug it into a setCursor function.
Second question comes from removing the moving cursor and just trying to display the values on a form. I can get the values to display, however it lags so unbelievably bad that maybe 1 value every 30 some seconds gets displayed. Tried doing delays on the sending arduino, setup a stopwatch if statement to slow down the set text functions, but it was still laggy. Is there a way to work with Serial transfer that doesn't make my computer want to die?
Here is the Visual Studio form code I have so far. Followed a tutorial to get the mouse coords and display them which worked amazing, so I tried to use the library for this as well with less luck.
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 Gma.System.MouseKeyHook;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace MoveMouseAuto
{
public partial class Form1 : Form
{
public Stopwatch watch { get; set; }
int potValue = 0;
String strPotValue = "";
[DllImport("user32.dll", SetLastError =true)]
public static extern bool SetCursorPos(int X, int Y);
private IKeyboardMouseEvents m_Events;
public Form1()
{
InitializeComponent();
}
private void Subscribe(IKeyboardMouseEvents events)
{
m_Events = events;
}
private void Unsubscribe()
{
if (m_Events == null) return;
m_Events.Dispose();
m_Events = null;
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "ON")
{
button1.Text = "OFF";
}
else if (button1.Text == "OFF")
{
button1.Text = "ON";
while (true)
{
if (watch.ElapsedMilliseconds > 200)
{
strPotValue = port.ReadLine();
//potValue = Convert.ToInt32(strPotValue);
//SetCursorPos(MousePosition.X + potValue, MousePosition.Y);
watch = Stopwatch.StartNew();
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
watch = Stopwatch.StartNew();
port.Open();
Unsubscribe();
Subscribe(Hook.GlobalEvents());
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Unsubscribe();
}
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessDialogKey(keyData);
}
}
}
And if needed, here is the Arduino code I wrote
int val;
void setup() {
Serial.begin(9600);
Serial.setTimeout(10);
}
void loop() {
Serial.println(getValue());
}
int getValue(){
val = analogRead(potPin) - 500;
return val;
}
I understand my question seems fairly vague but this is as specific as I can get with my very limited knowledge on the topic.
Thank you for your time.
I am making a password generator and on websites when you enter certain conditions are met the strength of the password changes how can I change the color and text of the label when the password strength is >= 8, <8<10, >12?
Here is 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 Password_Generator
{
public partial class PassGen : Form
{
int currentPasswordLength = 0;
Random Character = new Random();
private void PasswordGenerator(int PasswordLength)
{
String validChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$&?";
String randomPassword = "";
//25
for(int i = 0; i < PasswordLength; i++)
{
int randomNum = Character.Next(0, validChars.Length);
randomPassword += validChars[randomNum];
}
Password.Text = randomPassword;
}
public PassGen()
{
InitializeComponent();
PasswordLengthSlider.Minimum = 5;
PasswordLengthSlider.Maximum = 22;
PasswordGenerator(5);
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Copy_Click(object sender, EventArgs e)
{
Clipboard.SetText(Password.Text);
}
//52
private void PasswordLength_Click(object sender, EventArgs e)
{
}
private void PasswordLengthSlider_Scroll(object sender, EventArgs e)
{
PasswordLength.Text = "Password Length:" + " " + PasswordLengthSlider.Value.ToString();
currentPasswordLength = PasswordLengthSlider.Value;
PasswordGenerator(currentPasswordLength);
}
private void pswdStrengthTest()
{
if (currentPasswordLength <= 8)
{
pswdStrength.Text = "weak";
pswdStrength.ForeColor = Color.Red;
} else if (currentPasswordLength<= 9)
{
pswdStrength.Text = "ok";
pswdStrength.ForeColor = Color.Blue;
}
}
//78
private void pswdStrength_Click(object sender, EventArgs e)
{
}
}
}
If anyone could help me with this it would be greatly appreciated. This is based off a tutorial I found on YouTube. I'm not sure what the video is called but if it helps I could search for it and update my posting.
Try this:
Password.TextChanged += (s1, e1) =>
{
if (Password.Text.Length > 10)
pswdStrength.ForeColor = Color.Green
else if (Password.Text.Length > 8)
pswdStrength.ForeColor = Color.Blue
else
pswdStrength.ForeColor = Color.Red
};
Your code looks like a windows form application.
If you have for example one objetc txt_password, check to code some of these events:
TextChanged: this occurs when your textbox has been changed
Others events could be:
KeyPress or KeyDown
I am new to c#. I am learning graphic objects by doing a Hangman game.
I need to save two char arrays : first from the word to be searched in word_selection_proposal(), second from the word suggested by the other player in word_selection_analysis().
I was thinking in using a boolean variable named first to ensure if that is the first time the function txtWord_KeyPress is called or not, to distinguish the first ENTER from the first player to the player who is searching for the word. I understand my boolean is a local variable so it is reset to true each time ENTER is pressed.
Is there a possibility to count the number of times ENTER is pressed so then I can distinguish which function to call to save the arrays then I could save this data.
Please, see just below the code and a picture to understand the code.
Thank you 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 Hangman_Game
{
public partial class Hangman : Form
{
public Hangman()
{
InitializeComponent();
}
private void Hangman_Load(object sender, EventArgs e)
{
FillComboLetters();
comboLetters.Enabled = false;
btnTest.Enabled = false;
btnReplay.Enabled = false;
lblVictory.Text = "";
txtWord.Text = "Enter a word to search here";
txtWord.Focus();
}
private void FillComboLetters()
{
comboLetters.Items.Clear();
for (int k = 0; k < 26; k++)
{
comboLetters.Items.Add((char)('A' + k));
}
comboLetters.SelectedIndex = 0;
}
private void txtWord_Click(object sender, EventArgs e)
{
txtWord.Text = "";
txtWord.Focus();
}
private void txtWord_KeyPress(object sender, KeyPressEventArgs e)
{
Boolean first = true;
string message = txtWord.Text.ToUpper();
if ((e.KeyChar == (char) Keys.Enter) && first)
{
word_selection_proposal(message);
first = false;
}
if ((e.KeyChar == (char)Keys.Enter) && !first)
{
word_selection_analysis(message);
}
}
private void word_selection_proposal(string word)
{
char[] player1 = word.ToCharArray();
txtWord.Text = "Array copied, Now your turn";
}
private void word_selection_analysis(string word)
{
char[] player2 = word.ToCharArray();
txtWord.Text = "array copied";
txtWord.Focus();
}
}
}
I have three Forms in my project. Form2 Connects the Serial Port. Form1 writes and reads data from the Serial Port. Form 3 only needs to write to the serial port, however when i send data to the serial port I get an "Port is closed error". I do not see any difference in the way i set up form 2 and form 3 so i am not sure why Visual Studios is giving me the "port closed" error.
Form 2 will connect to serial port
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; // added this
namespace ECE_323_LAB_10
{
public partial class Bluetooth_Settings : Form
{
public SerialPort _serial = new SerialPort(); // added this
public Bluetooth_Settings()
{
InitializeComponent();
_serial.BaudRate = int.Parse(baud_rate.Text); // added this
foreach (string s in SerialPort.GetPortNames()) // added this
{
com_port.Items.Add(s);
}
}
private void connet_button_Click(object sender, EventArgs e)
{
try
{
_serial.PortName = com_port.SelectedItem.ToString();
_serial.BaudRate = Convert.ToInt32(baud_rate.SelectedItem);
_serial.Open();
this.Close();
Form1 _main = new Form1();
foreach (Form1 tmpform in Application.OpenForms)
{
if (tmpform.Name == "Form1")
{
_main = tmpform;
break;
}
}
_main.toolStripStatusLabel1.Text = " Connected: " + _serial.PortName.ToString();
_main.toolStripStatusLabel1.ForeColor = Color.Green;
_main.toolStripProgressBar1.Value = 100;
}
catch
{
MessageBox.Show("Please select COM Port/ Baud Rate");
}
}
}
}
Form1 can read and write data to serial port
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 ZedGraph;
using System.Text.RegularExpressions;
namespace ECE_323_LAB_10
{
public partial class Form1 : Form
{
PointPairList list = new PointPairList();
double temp;
int flag = 1;
double x = 0;
int init = 0;
int digit = 0;
double temp1;
private T_settings t_settings;
private Bluetooth_Settings _setting = new Bluetooth_Settings();
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
int text_length = 0;
text_length = richTextBox1.TextLength;
char send_ch = richTextBox1.Text[text_length - 1]; // extracting the last character
char[] ch = new char[1];
ch[0] = send_ch;
if (send_ch == '\n')
{
_setting._serial.Write("\r"); // sending carraige return
}
else
{
_setting._serial.Write(ch, 0, 1); // sending char to microcontroller
}
}
private void Toggle_Click(object sender, EventArgs e)
{
// 2 = F , 1 = C
char[] ch = new char[1];
ch[0] = 'D';
_setting._serial.Write(ch, 0, 1); // sending char to microcontroller
}
private void Settings_Click(object sender, EventArgs e)
{
t_settings = new T_settings();
t_settings.Show();
}
}
}
Form1 has no errors when i read and write to the serial port. I have left a few lines of codes out for readability.
Now here is the code for Form3, I think i have done setup exactly the same as Form1, however I am getting port is closed error.
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; // added this
namespace ECE_323_LAB_10
{
public partial class T_settings : Form
{
private Bluetooth_Settings _enter = new Bluetooth_Settings();
public T_settings()
{
InitializeComponent();
}
string Sampling_text;
private void Text_Sampling_TextChanged(object sender, EventArgs e)
{
Sampling_text = Text_Sampling.Text;
}
private void Send_Sampling_Click(object sender, EventArgs e)
{
int text_length = 0;
text_length = Sampling_text.Length;
char send_ch = Text_Sampling.Text[text_length - 1]; // extracting the last character
char[] ch = new char[1];
ch[0] = send_ch;
if (send_ch == '\n')
{
_enter._serial.Write("\r"); // sending carraige return
}
else
{
_enter._serial.Write(ch, 0, 1); // sending char to microcontroller
}
char[] enter = new char[1];
}
}
}
Can someone tell me what I need to add to Form3 so I do not get a port closed error. In my send sampling click method.
Ok, if you're totally new then concepts around OOP will take time to learn. Let me try and give you a solution to get you out of trouble.
private T_settings t_settings = null;
private Bluetooth_Settings _bsSettings = null;
public Form1()
{
InitializeComponent();
if (_bsSettings == null) _bsSettings = new Bluetooth_Settings();
_bsSettings.Show();
}
private void Form1_Shown(Object sender, EventArgs e) {
{
//Either here or in the constructor instantiate T_settings with a reference to the
//_bsSettings this way it will still be in scope, the same instance you've connected.
if (t_settings == null) t_settings = new T_settings(_bsSettings);
}
public partial class T_settings : Form
{
private Bluetooth_Settings _bsSettings = new Bluetooth_Settings();
public T_settings(Bluetooth_Settings bsSettings)
{
InitializeComponent();
//Pass a reference of the BS Settings class (one that's already connected)
this._bsSettings = bsSettings;
}
...
private void Send_Sampling_Click(object sender, EventArgs e)
{
int text_length = 0;
text_length = Sampling_text.Length;
char send_ch = Text_Sampling.Text[text_length - 1]; // extracting the last character
char[] ch = new char[1];
ch[0] = send_ch;
if (send_ch == '\n')
{
_bsSettings._serial.Write("\r"); // sending carraige return
}
else
{
_bsSettings._serial.Write(ch, 0, 1); // sending char to microcontroller
}
}
I have a program that gets the incoming number, date and time. I want to check however if the person who is ringing me has put the phone down, how can I do this?
Below is the code which I currently have:
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.IO.Ports;
namespace CallerID
{
public partial class CallerID : Form
{
int timesTicked = 0;
Point defaultLocation = new Point();
Point newLocation = new Point();
public CallerID()
{
InitializeComponent();
port.Open();
SetModem(); // SetModem(); originally went after WatchModem();
WatchModem();
//SetModem();
telephoneTimer.Interval = 16;
telephoneTimer.Tick += new EventHandler(telephoneTimer_Tick);
defaultLocation = pictureBox1.Location;
newLocation = pictureBox1.Location;
}
void telephoneTimer_Tick(object sender, EventArgs e)
{
if (timesTicked <= 2)
newLocation.X++;
if (timesTicked >= 4)
newLocation.X--;
if (timesTicked == 6)
{
timesTicked = 0;
pictureBox1.Location = defaultLocation;
newLocation = defaultLocation;
}
pictureBox1.Location = newLocation;
timesTicked++;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
WatchModem();
}
private SerialPort port = new SerialPort("COM3");
string CallName;
string CallNumber;
string ReadData;
private void SetModem()
{
port.WriteLine("AT+VCID=1\n");
//port.WriteLine("AT+VCID=1");
port.RtsEnable = true;
}
private void WatchModem()
{
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
public delegate void SetCallerIdText();
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
ReadData = port.ReadExisting();
//Add code to split up/decode the incoming data
//if (lblCallerIDTitle.InvokeRequired)
if (ReadData.Contains("NMBR"))
{
lblData.Invoke(new SetCallerIdText(() => lblData.Text = ReadData));
}
//else
// lblCallerIDTitle.Text = ReadData;
}
private void lblData_TextChanged(object sender, EventArgs e)
{
telephoneTimer.Start();
button1.Visible = true;
}
}
}
Please ignore the Timer Code as that is just for animation.
Have you tried the PinChanged event? Normally Carrier Detect will go low when the remote end disconnects.