I understand that when Thread.Sleep is being executed, the buttons on my GUI are not able to be clicked on.
Is there any other ways to delay my codes from flowing yet still able to click on my buttons on the GUI?
For example right now after my codes execute Thread.Sleep(10000); and within this 10 seconds i'm not able to click on my button1 event, is there anyway that I can still click on my button1 event within these 10 seconds?
private void displaydata_event2(object sender, EventArgs e)
{
txt_data.AppendText(in_data + "\n");
string inStr;
inStr = in_data;
//MessageBox.Show(inStr.Length.ToString());
if (inStr.Length == 12)
{
int indexOfSpace = inStr.IndexOf(' ');
string Patient = inStr.Substring(indexOfSpace + 1);
int rx = 0;
int selected = 0;
txtData1.Text = Patient;
rx = Convert.ToInt16(Patient);
selected = Convert.ToInt16(txt_pnorec.Text);
if (rx != selected)
{
MessageBox.Show("Please check patient settings");
}
}
else if (inStr.Length == 24)
{
label2.Text = "Patient is not selected!";
label2.BackColor = Color.Red;
}
else if (inStr.Length == 10)
{
int indexOfSpace = inStr.IndexOf(':');
string Temp = inStr.Substring(indexOfSpace + 1);
txtData2.Text = Temp;
double tempflo;
tempflo = Convert.ToDouble(Temp);
if (tempflo > 20)
{
lbl_temp.Text = "Fever";
lbl_temp.BackColor = Color.Red;
}
}
else if (inStr.Length == 9)
{
int indexOfSpace = inStr.IndexOf(':');
string ECG = inStr.Substring(indexOfSpace + 1);
txtData3.Text = ECG;
}
else if (inStr.Length == 19 || inStr.Length == 20)
{
int indexOfSpace = inStr.IndexOf(':');
string Systolic = inStr.Substring(indexOfSpace + 1);
txtData4.Text = Systolic;
}
else if (inStr.Length == 21 || inStr.Length == 22)
{
int indexOfSpace = inStr.IndexOf(':');
string Diastolic = inStr.Substring(indexOfSpace + 1);
txtData5.Text = Diastolic;
}
else if (inStr.Length == 16)
{
int indexOfSpace = inStr.IndexOf(':');
string Pulse = inStr.Substring(indexOfSpace + 1);
txtData6.Text = Pulse;
}
else if (inStr.Length == 23 || inStr.Length == 17 || inStr.Length == 27 || inStr.Length == 30 || inStr.Length == 35 || inStr.Length == 29)
{
lbl_bp.Text = inStr;//to display status of BP (Normal,prehypotension etc)
string bp;
bp = inStr;
if (bp.Length == 23 || bp.Length == 27 || bp.Length == 31 || bp.Length == 35 || bp.Length == 30)
{
lbl_bp.BackColor = Color.Red;
}
else if (bp.Length == 17)
{
lbl_bp.BackColor = Color.LightGray;
}
}
else if (inStr.Length == 32 || inStr.Length == 25 || inStr.Length == 34 || inStr.Length == 33 || inStr.Length == 26 || inStr.Length == 31)
{
int indexOfSpace = inStr.IndexOf(':');
string Acc = inStr.Substring(indexOfSpace + 1);
txtData7.Text = Acc;
string test = inStr;
if (test.Length == 25 || test.Length == 34 || test.Length == 33 || test.Length == 26)
{
label21.Text = "Check on patient!";
label21.BackColor = Color.Red;
}
else if (test.Length == 32)
{
label21.Text = "";
label21.BackColor = Color.LightGray;
}
}
else
{
}
if (txtData1.Text != "" && txtData2.Text != "" && txtData3.Text != "" && txtData4.Text != "" && txtData5.Text != "" && txtData6.Text != "" && txtData7.Text != "")
{
try
{
connection2.Open();
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection2;
command2.CommandText = "insert into MedicalRecord (PatientNumber,FirstName,LastName,IC,Temperature,ECG,Systolic,Diastolic,Pulse) values('" + txt_pnorec.Text + "','" + txt_fnamerec.Text + "','" + txt_lnamerec.Text + "','" + txt_icrec.Text + "','" + txtData2.Text + "','" + txtData3.Text + "','" + txtData4.Text + "','" + txtData5.Text + "','" + txtData6.Text + "')";
command2.ExecuteNonQuery();
MessageBox.Show("Info Stored");
connection2.Close();
txtData1.Text = "";
txtData2.Text = "";
txtData3.Text = "";
txtData4.Text = "";
txtData5.Text = "";
txtData6.Text = "";
txtData7.Text = "";
Thread.Sleep(interval);
MessageBox.Show("Start");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
txtData1.Text = "";
txtData2.Text = "";
txtData3.Text = "";
txtData4.Text = "";
txtData5.Text = "";
txtData6.Text = "";
txtData7.Text = "";
}
}
Thanks in advance.
There are multiple ways to achieve this. One example is to use a task with a delay:
Task.Delay(10000).ContinueWith(x =>
{
//Place the code you want delayed here.
});
Another example could be to use a BackgroundWorker which is made for this exact purpose.
you can use Async and Await
here is a good tutorial in combination with an GUI:
https://www.youtube.com/watch?v=MCW_eJA2FeY
you need to declare your function as async
public async void Foo()
{
...
}
than you can use:
await Task.Delay(10000);
it will release you GUI for the whole Delay and you can use your GUI while the Delay is waiting.
Task.Delay(10000).ContinueWith(x =>
{
//...
});
Have a look at Task.Delay and ContinueWith.
You can use Windows.Forms.Timer to execute something after delay... (with no UI thread freezing). Split your code on two parts. 1. Before delay 2. After delay
public partial class form1 : Form
{
// i used namespace to ensure that we use 'correct' Timer and we do not
// confuse it with System.Timers.Timer or System.Threading.Timer
System.Windows.Forms.Timer tmrDelay;
void SomeMethodWithDelay()
{
// code before delay here
tmrDelay.Enabled = true;
tmrDelay.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
Thread.Sleep(5000);
// your code here
// disables timer to stop it
tmrDelay.Enabled = false;
}
}
Benefit from using Timer is that it is a native windows forms tool that was specially designed to help with this kind of problems.
However you can still use modern things like Tasks, for example : Task.Factory.StartNew(() => { Thread.Sleep(5000); // your method logic here });
Related
I have a RichTextBox in a C# project. Adding characters and counting the number of characters per line works.
The issue comes when I try to delete characters with the Backspace Key
I have commented out the code I have tried while pressing the Backspace Key
I also tried to use a KeyPress event to manage counting characters deleted complete fail.
If anyone would like to test the code here are the properties of the RichTextBox Name rtbInfo.
Size 347 by 120 Font 10.8 Bold WordWrap False NO Scroll Bars Max Length 135
GOAL Increase the variable res by 1 for each character or space deleted with the press of the Backspace Key.
I would prefer to not use KeyPress KeyUp or KeyDown Events if at all possible.
Happy to consider code suggestions with those Event designs.
public partial class frmRTB : Form
{
int Count = 0;
int Lines = 0;
int cT = 0;
int res = 0;
public frmRTB()
{
InitializeComponent();
//rtbInfo.KeyPress += rtbInfo_KeyPress;
/*=== This Must be here to register rtbInfo ===*/
/*=============================================*/
}
private void frmRTB_Load(Object sender, EventArgs e)
{
ActiveControl = rtbInfo;
}
/*private void rtbInfo_KeyPress(object sender, KeyPressEventArgs e)
{
if (rtbInfo.TextLength == 0)
{
tbMessage.Text = "Nothing to Delete";
return;
}
if (e.KeyChar == ((char)Keys.Back) & (char.IsControl('\b')))
{
//rtbInfo.Text = rtbInfo.Text.Remove(rtbInfo.TextLength - 1, 0);
//rtbInfo.Select(rtbInfo.TextLength - 0, 0);
//rtbInfo.ScrollToCaret();
//cT = cT - 1;
//res = - 1;// Last edit was res - cT ?
//tbCount.Text = "Back Fire";
//e.Handled = true;
}
}*/
public void rtbInfo_TextChanged(Object sender, EventArgs e)
{
Count = rtbInfo.TextLength;
Lines = rtbInfo.Lines.Length;
foreach (char chr in rtbInfo.Text)
{
if (char.IsLetterOrDigit(chr))
{
cT = cT + 1;
res = 33 - cT;
}
/*
Regex regex = new Regex(#"^[\b]+$");
//Regex regex = new Regex(#"^[\b\S\t\D\W]+$");
if (regex.IsMatch(rtbInfo.Text))
{
tbCount.Text = "Use BACKSPACE Key to Edit";
}*/
//if (chr == '\b')
//if (chr == ((char)Keys.Back))
// tried above if statments they do not fire
// This fires when any key is entered NOT just the Backspace key
/*if (char.IsControl('\b'))// & !(char.IsLetterOrDigit(chr)))
{
//rtbInfo.Text = rtbInfo.Text.Remove(rtbInfo.TextLength - 1, 0);
//rtbInfo.Select(rtbInfo.TextLength - 0, 0);
//rtbInfo.ScrollToCaret();
res = +1;
tbCount.Text = "Use BACKSPACE Key to Edit";
}*/
if (Lines == 5 | Count == 135)
{
rtbInfo.ReadOnly = true;
}
if (rtbInfo.ReadOnly == true)
{
txtBoxMsg.Text = "";
tbMessage.Text = "";
tbCount.Text = "Use BACKSPACE Key to Edit";
}
if (rtbInfo.Text.EndsWith("\n"))
{
cT = 0;
res = 0;
}
if (cT == 33)
{
SendKeys.Send("{ENTER}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
cT = 0;
res = 0;
}
if (rtbInfo.ReadOnly == true)
{
string message = "Press YES to edit Notes" + '\n' + " NO Clear Notes";
string title = "Edit Notes";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result = MessageBox.Show(message, title, buttons);
if (result == DialogResult.Yes)
{
rtbInfo.ReadOnly = false;
SendKeys.Send("{BACKSPACE}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
cT = 0;
res = 0;
}
else
{
rtbInfo.ReadOnly = false;
rtbInfo.Clear();
tbCount.Text = "All Notes Remove";
}
}
if (res == 0)
{
res = 33;
}
txtBoxMsg.Text = "Total of " + (135 - Count) + " can be entered & " + (5 - Lines) + " Lines";
tbMessage.Text = "Total of " + res + " more char can be entered on line " + Lines;
//tbCount.Text = "Count is " + Count + " cT " + cT + " res " + res;// For Testing
return;
}
I solved this using both TextChanged & KeyPress events
While that solution worked I decided to put all the code in a KeyPress event ONLY.
One HUGE mistake in my original question was in InitializeComponent
Look up and read when & how to use this method. Enjoy the Code
public partial class frmKPO : Form
{
int rtbTotLen;
int linesTot;
int lineNum;
int res1;
int count1;
int res2;
int count2;
int res3;
int count3;
int res4;
int count4;
public frmKPO()
{
InitializeComponent();
}
private void rtbInfo_KeyPress(object sender, KeyPressEventArgs e)
{
rtbTotLen = rtbInfo.TextLength;
linesTot = rtbInfo.Lines.Length;
lineNum = (5 - linesTot);
txtBoxMsg.Text = "Total of " + (135 - rtbTotLen) + " can be entered on " + (5 - lineNum) + " Lines";
if (e.KeyChar == (char)Keys.Back)
{
if (lineNum == 1)
{
--res1;
}
if (lineNum == 2)
{
--res2;
}
if (lineNum == 3)
{
--res3;
}
if (lineNum == 4)
{
--res4;
}
}
else
{
if (lineNum == 1)
{
++res1;
}
if (lineNum == 2)
{
++res2;
}
if (lineNum == 3)
{
++res3;
}
if (lineNum == 4)
{
++res4;
}
}
if (lineNum == 4)
{
count4 = 33 - res4;
tbMessage.Text = "Total of " + count4 + " more char can be entered on line " + (5 - lineNum) + "";
if (count4 == 0)
{
SendKeys.Send("{ENTER}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
}
}
else if (lineNum == 3)
{
count3 = 33 - res3;
tbMessage.Text = "Total of " + count3 + " more char can be entered on line " + (5 - lineNum) + "";
if (count3 == 0)
{
SendKeys.Send("{ENTER}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
}
}
else if (lineNum == 2)
{
count2 = 33 - res2;
tbMessage.Text = "Total of " + count2 + " more char can be entered on line " + (5 - lineNum) + "";
if (count2 == 0)
{
SendKeys.Send("{ENTER}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
}
}
else if (lineNum == 1)
{
count1 = 33 - res1;
tbMessage.Text = "Total of " + count1 + " more char can be entered on line " + (5 - lineNum) + "";
if (count1 == 0)
{
SendKeys.Send("{ENTER}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
}
}
if (linesTot == 5 | rtbTotLen == 135)
{
rtbInfo.ReadOnly = true;
}
if (rtbInfo.ReadOnly == true)
{
txtBoxMsg.Text = "";
tbMessage.Text = "";
tbCount.Text = "Use BACKSPACE Key to Edit";
}
if (rtbInfo.ReadOnly == true)
{
txtBoxMsg.Text = "";
tbMessage.Text = "";
tbCount.Text = "Use BACKSPACE Key to Edit";
string message = "Press YES to edit Notes" + '\n' + " NO Clear Notes";
string title = "Edit Notes";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result = MessageBox.Show(message, title, buttons);
if (result == DialogResult.Yes)
{
rtbInfo.ReadOnly = false;
SendKeys.Send("{BACKSPACE}");
rtbInfo.ScrollToCaret();
rtbInfo.Focus();
}
else
{
rtbInfo.ReadOnly = false;
rtbInfo.Clear();
tbCount.Text = "All Notes Remove";
}
}
}
private void btnToStart_Click(object sender, EventArgs e)
{
Close();
frmStart fS = new frmStart();
fS.Show();
}
private void frmKPO_Load(object sender, EventArgs e)
{
ActiveControl = rtbInfo;
tbMessage.Text = "Total of " + 33 + " more char can be entered on line " + 1 + "";
}
}
I usually know how to replace a do..while loop with a for loop, but in this case variable check2 is used 2 times for different loops with got me confused on how to correctly replace it with for loop.
public static void RelayChat(ref int con, ref string Message)
{
string temp_SubName = "relaychat";
WriteSub(ref temp_SubName);
int check2 = 0;
if (Message.Length == 0) return;
var check = UserConToCheck(con);
if (CheckMute(get_UserName(check)) || get_UserChat(check) > 4) return;
if (get_UserChat(check) < 8) set_UserChat(check, get_UserChat(check) + 1);
if (Message.Length > 100) Message = Message.Substring(0, 99);
if (Message[0] == '!')
{
if (UserCommand(con, Message.Substring(1).Split(" ".ToCharArray()))) return;
}
if (PlayerAdapter.get_Reference(check).get_IsAdmin(1))
{
if (Message.Substring(0, 1) == "#")
{
string[] temp_cmds = Message.Substring(1).Split(",".ToCharArray());
admin.AdminCommand(PlayerAdapter.get_Reference(check), ref temp_cmds);
return;
}
}
if (Message.StartsWith(":g::", true, null))
{
do
{
check2++;
var guild1 = get_UserGuild(check);
var guild2 = get_UserGuild(check2);
if (guild1 == null || guild2 == null || guild1.ToLower() != guild2.ToLower()) continue;
var thisuser = get_UserName(check);
var targetuser = get_UserName(check2);
var found = targetuser != null && thisuser != null &&
IgnoreUserList.ContainsKey(targetuser) &&
IgnoreUserList[targetuser].Contains(thisuser);
if (found == false)
{
Winsock.PrivMsg(get_UserCon(check2), "14,1,[ " + get_UserGuild(check2) + " ] Chat - " + get_UserName(check) + " : " + Message.Substring(4));
}
} while (check2 != UserMax);
return;
}
if (check <= 0) return;
do
{
check2++;
bool found = false;
var user = get_UserName(check2);
if (user != null && IgnoreUserList.ContainsKey(user))
{
found = Convert.ToBoolean(IgnoreUserList[get_UserName(check2)].Contains(get_UserName(check)));
}
if (found) return;
if (get_UserLanded(check2) != get_UserLanded(check)) return;
if (get_UserLanded(check2))
{
if (get_UserInBar(check2) == false &&
get_UserInUniversalBar(check2) == false) return;
if (get_UserInUniversalBar(check2) && get_UserInUniversalBar(check))
{
Winsock.PrivMsg(get_UserCon(check2), "13,0,[ " + get_UserName(check) + " ] : " + Message);
}
else if (get_UserInBar(check2) && get_UserInBar(check))
{
if (get_UserLastPlanet(check2) !=
get_UserLastPlanet(check)) return;
Winsock.PrivMsg(get_UserCon(check2), "13,0,[ " + get_UserName(check) + " ] : " + Message);
}
}
else if (get_UserLanded(check2) == false)
{
if (get_UserSector(check2) != get_UserSector(check)) return;
if (get_UserZone(check2) != get_UserZone(check)) return;
Winsock.PrivMsg(get_UserCon(check2), "13,0,[ " + get_UserName(check) + " ] : " + Message);
}
} while (check2 != UserMax);
}
I know that the function might be a lot complex, but please ignore that fact and focus on just the do..while loops. Thank you!
Just declare the for loop to use the existing variable.
int check2 = 0;
if (Message.StartsWith(":g::", true, null))
{
for (; check2 < UserMax; check2++)
{
// Do stuff
}
return;
}
if (check <= 0) return;
for (; check2 < 200; check2++)
{
// Do stuff
}
I made a c# project that lists certain things in ListViews, but the ListViewsare a little annoying, they don't work everytime, sometimes the input is correct and can be displayed in a MessageBox or ListBox but nothing happens when trying to add it to the ListBox, this is my code right now and nothing happens when pressing the button.
private async void button2_Click(object sender, EventArgs e)
{
if(shouldirefresh == true)
{
button2.Enabled = false;
checkBox1.Enabled = false;
checkBox2.Enabled = false;
checkBox3.Enabled = false;
checkBox4.Enabled = false;
checkBox5.Enabled = false;
checkBox6.Enabled = false;
pictureBox1.Visible = true;
webBrowser1.Refresh();
await td(3500);
}
checkBox1.Text = "Highlight -50%";
checkBox2.Text = "Highlight 100%";
checkBox3.Text = "Highlight 50%";
pictureBox1.Visible = true;
min50 = 0;
max100 = 0;
eq50 = 0;
listView1.Items.Clear();
listBox1.Items.Clear(); listBox2.Items.Clear(); listBox3.Items.Clear(); listBox4.Items.Clear();
lsttit.Clear(); lstpoint.Clear(); lstmaxwosl.Clear(); lstmax.Clear();
HtmlDocument doc = this.webBrowser1.Document;
doc = webBrowser1.Document;
var links = PulseVar.myrodoc.GetElementsByTagName("td");
foreach (HtmlElement link in links)
{
if (link.GetAttribute("className") == "title")
{
lsttit.Add(link.InnerText);
}
else if (link.GetAttribute("className") == "point" || link.GetAttribute("className") == "point tekort")
{
lstpoint.Add(link.InnerText);
}
else if (link.GetAttribute("className") == "max" || link.GetAttribute("className") == "max tekort")
{
string RM = link.InnerText.Remove(0, 1);
lstmax.Add(RM);
}
else if (link.GetAttribute("className") == "date")
{
datez.Add(link.InnerText);
}
else if(link.GetAttribute("className") == "average")
{
lstav.Add(link.InnerText);
}
else if(link.GetAttribute("className") == "comment")
{
if(link.InnerText == " ")
{
lstcomment.Add(" ");
}
else
{
lstcomment.Add(link.InnerText);
}
}
else if(link.GetAttribute("className") == "TeacherTitle")
{
this.Text = "Myro ~ " + link.InnerText;
}
}
for (int i = 0; i <= lsttit.Count - 1; i++)
{
ListViewItem d = new ListViewItem(lsttit[i]);
try
{
if (decimal.Parse(lstpoint[i]) < (decimal.Parse(lstmax[i]) / 2))
{
min50++;
d.SubItems.Add(lstpoint[i] + "/" + lstmax[i]);
if (checkBox1.Checked == true)
{
d.ForeColor = Color.Red;
}
}
else if (decimal.Parse(lstpoint[i]) == (decimal.Parse(lstmax[i])))
{
//listView2.Items.Add(lstpoint[i] + "/" + lstmax[i]);
d.SubItems.Add(lstpoint[i] + "/" + lstmax[i]);
if (checkBox2.Checked == true)
{
d.ForeColor = Color.Green;
}
max100++;
}
else if (decimal.Parse(lstpoint[i]) == (decimal.Parse(lstmax[i]) / 2))
{
//listView2.Items.Add(lstpoint[i] + "/" + lstmax[i]);
d.SubItems.Add(lstpoint[i] + "/" + lstmax[i]);
if (checkBox3.Checked == true)
{
d.ForeColor = Color.Yellow;
}
eq50++;
}
else
{
d.SubItems.Add(lstpoint[i] + "/" + lstmax[i]);
//listView2.Items.Add(lstpoint[i] + "/" + lstmax[i]);
}
}
catch (Exception)
{
//listView2.Items.Add(lstpoint[i] + "/" + lstmax[i]);
d.SubItems.Add(lstpoint[i] + "/" + lstmax[i]);
}
d.SubItems.Add(datez[i]);
d.SubItems.Add(lstav[i] + "/" + lstmax[i]);
d.SubItems.Add(lstcomment[i]);
listView1.Items.Add(d);
}
checkBox1.Text += "(" + min50.ToString() + ")";
checkBox2.Text += "(" + max100.ToString() + ")";
checkBox3.Text += "(" + eq50.ToString() + ")";
pictureBox1.Visible = false;
//groupBox1.Location = new Point(12, 12);
checkBox5.Checked = false;
button2.Enabled = true;
checkBox1.Enabled = true;
checkBox2.Enabled = true;
checkBox3.Enabled = true;
checkBox4.Enabled = true;
checkBox5.Enabled = true;
checkBox6.Enabled = true;
shouldirefresh = true;
label3.Text = DateTime.Now.ToString("dd/MM/yyyy hh:mm");
}
Again if I do MessageBox.Show(lsttit[i]); it shows the correct data everytime, my ListView has the correct columns and is set to details but nothing happens at all....
what's wrong here?
I'm trying to wait for 20 seconds before adding + 1 value to i (Int), But i want to do it without Thread.Sleep.
This is my code, By the way I'm not a Pro programmer.
private void Refresh_App_TimerNH_Tick(object sender, EventArgs e)
{
label18.Text = "Timer Activated";
int i = 0;
i = i + 1;
if (i == 16)
{
i = 0;
}
else
{
}
if (i == 1)
{
webBrowser1.Refresh();
userIdLabel1.BackColor = Color.Red;
label20.Text = "+1";
//**i want to add 20 second gap here**
i = i + 1;
}
else
{
}
if (i == 2)
{
webBrowser2.Refresh();
userIdLabel2.BackColor = Color.Red;
label20.Text = "+2";
i = i + 1;
}
else
{
}
if (i == 3)
{
webBrowser3.Refresh();
userIdLabel3.BackColor = Color.Red;
label20.Text = "+3";
i = i + 1;
}
else
{
}
if (i == 4)
{
webBrowser4.Refresh();
userIdLabel4.BackColor = Color.Red;
label20.Text = "+4";
i = i + 1;
}
else
{
}
if (i == 5)
{
webBrowser5.Refresh();
userIdLabel5.BackColor = Color.Red;
label20.Text = "+5";
i = i + 1;
}
else
{
}
if (i == 6)
{
webBrowser6.Refresh();
userIdLabel6.BackColor = Color.Red;
label20.Text = "+6";
i = i + 1;
}
else
{
}
if (i == 7)
{
webBrowser7.Refresh();
userIdLabel7.BackColor = Color.Red;
label20.Text = "+7";
i = i + 1;
}
else
{
}
if (i == 8)
{
webBrowser8.Refresh();
userIdLabel8.BackColor = Color.Red;
label20.Text = "+8";
i = i + 1;
}
else
{
}
if (i == 9)
{
webBrowser9.Refresh();
userIdLabel9.BackColor = Color.Red;
label20.Text = "+9";
i = i + 1;
}
else
{
}
if (i == 10)
{
webBrowser10.Refresh();
userIdLabel10.BackColor = Color.Red;
label20.Text = "+10";
i = i + 1;
}
else
{
}
if (i == 11)
{
webBrowser11.Refresh();
userIdLabel11.BackColor = Color.Red;
label20.Text = "+11";
i = i + 1;
}
else
{
}
if (i == 12)
{
webBrowser12.Refresh();
userIdLabel12.BackColor = Color.Red;
label20.Text = "+12";
i = i + 1;
}
else
{
}
if (i == 13)
{
webBrowser13.Refresh();
userIdLabel13.BackColor = Color.Red;
label20.Text = "+13";
i = i + 1;
}
else
{
}
if (i == 14)
{
webBrowser14.Refresh();
userIdLabel14.BackColor = Color.Red;
label20.Text = "+14";
i = i + 1;
}
else
{
}
if (i == 15)
{
webBrowser15.Refresh();
userIdLabel15.BackColor = Color.Red;
label20.Text = "+15";
i = i + 1;
}
else
{
}
if (i == 16)
{
webBrowser16.Refresh();
userIdLabel16.BackColor = Color.Red;
label20.Text = "+16";
i = i + 1;
}
else
{
}
Refresh_App_TimerNH.Stop();
label18.Text = "Timer De-Activated";
Refresh_App_TimerNH.Start();
}
I think it might be easy but not for me, Because i'm new to c#
First off, Tim S's answer -- break up your logic into smaller chunks and simplify the timer logic -- is good. But to answer your specific question, which was "how do I delay between statements without Sleep", is: make the method async and then use await Task.Delay(...).
You are right to avoid Sleep; using it is a bad programming practice, and will hang your application. await Task.Delay does an asynchronous wait -- that is, the method returns immediately, the app keeps on processing UI messages, and when the delay is done, the program schedules the remainder of the method to execute later.
Note that during an asynchronous wait, by design messages keep on getting processed. If one of those messages causes your event handler to run again then you can get into the very confusing situation of having multiple control points in the same non-recursive method. Try to avoid that.
Right now your logic is convoluted, and probably very different from what you want it to do.
Your code will be much simpler if you put your webBrowserX and userIdLabelX items in some sort of list together.
public class MyPair
{
public WebBrowser WebBrowser { get; set; }
public Label UserIdLabel { get; set; }
}
private List<MyPair> pairs;
private int refreshIndex = 0;
private void StartTimer()
{
pairs = // populate pairs somehow
refreshIndex = 0;
var timer = new System.Windows.Forms.Timer();
timer.Interval = 20000
timer.Tick += MyTickHandler;
timer.Start();
label18.Text = "Timer Activated";
}
private void MyTickHandler(object sender, EventArgs e)
{
pairs[refreshIndex].WebBrowser.Refresh();
pairs[refreshIndex].UserIdLabel.BackColor = Color.Red;
label20.Text = "+" + (refreshIndex + 1);
refreshIndex = (refreshIndex + 1) % pairs.Count;
}
Note that this timer never deactivates, it loops through the list of pairs repeatedly.
i have code to format telephone number automatically,
format is 12 3456-7890
1234567890 = 12 3456-7890 (TextLength = 12)
I want if TextLength = 13 format this way
12345678901 = 12 34567-8901 (TextLength = 12) or in another words, change postion of "-" to 1 position right and add last number on last character
my actual code
private void txtFonecom_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
}
else
{
if (txtFonecom.TextLength == 2)
{
txtFonecom.Text = txtFonecom.Text + " ";
txtFonecom.SelectionStart = 3;
txtFonecom.SelectionLength = 0;
}
if (txtFonecom.TextLength == 7)
{
txtFonecom.Text = txtFonecom.Text + "-";
txtFonecom.SelectionStart = 8;
txtFonecom.SelectionLength = 0;
}
if (txtFonecom.TextLength == 13)
{
//here i have to change format from 12 3456-7890 to 12 34567-8901
}
}
}
Instead of manually handling the keypresses I would suggest using the MaskedTextBox control with the mask 00 0000-0000 since the control can automatically format the input for you.
Assuming you still prefer to go for a TextBox solution here is the solution:
private void txtFonecom_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
}
else
{
if (txtFonecom.TextLength == 2)
{
txtFonecom.Text = txtFonecom.Text + " ";
txtFonecom.SelectionStart = 3;
txtFonecom.SelectionLength = 0;
}
if (txtFonecom.TextLength == 7)
{
txtFonecom.Text = txtFonecom.Text + "-";
txtFonecom.SelectionStart = 8;
txtFonecom.SelectionLength = 0;
}
if (txtFonecom.TextLength == 12)
{
int caretPos = txtFonecom.SelectionStart;
txtFonecom.Text = txtFonecom.Text.Replace("-", string.Empty).Insert(8, "-");
txtFonecom.SelectionStart = caretPos;
}
}
}
Keep in mind you will need to handle the format when the user deletes numbers.
This code will keep the " " and "-" at their places whether user remove or add numbers at any where:
void txtFonecom_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Back)
{
if (txtFonecom.TextLength == 2)
{
txtFonecom.Text = txtFonecom.Text + " ";
txtFonecom.SelectionStart = 3;
}
if (txtFonecom.TextLength >= 7 && txtFonecom.TextLength < 12)
{
if (txtFonecom.Text.Substring(2, 1) == " ") //check if " " exists
{ }
else //if doesn't exist, then add " " at index 2 (character no. 3)
{
txtFonecom.Text = txtFonecom.Text.Replace(" ", String.Empty);
txtFonecom.Text = txtFonecom.Text.Insert(2, " ");
}
txtFonecom.Text = txtFonecom.Text.Replace("-", String.Empty); //now add "-" at index 7 (character no. 8)
txtFonecom.Text = txtFonecom.Text.Insert(7, "-");
txtFonecom.SelectionStart = txtFonecom.Text.Length;
}
if (txtFonecom.TextLength >= 12)
{
if (txtFonecom.Text.Substring(2, 1) == " ") //check if " " exists
{ }
else //if doesn't exist, then add " " at index 2 (character no. 3)
{
txtFonecom.Text = txtFonecom.Text.Replace(" ", String.Empty);
txtFonecom.Text = txtFonecom.Text.Insert(2, " ");
}
txtFonecom.Text = txtFonecom.Text.Replace("-", String.Empty); //now add "-" at index 8 (character no. 9)
txtFonecom.Text = txtFonecom.Text.Insert(8, "-");
txtFonecom.SelectionStart = txtFonecom.Text.Length;
}
}
}
Or if you only want numbers in textbox, then use
if ((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57)