I want to make a button run some code, then press itself again in Windows Forms.
When I call the button itself I get the error:
System.StackOverflowException
HResult=0x800703E9
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
I want to make a resource monitor program to get myself familiarized with C#. Right now I'm stuck at the string processing and displaying a constantly changing string. I'm using a randomly generated number as a placeholder, that I want to show and change permanently, imitating real data pulling.
The code I have:
public void Start_Click(object sender, EventArgs e){
var usage =new CpuUsage(); //placeholder class for getting the CPU use data
usage.setCPU(); //gets a random number
this.CPU.Text = usage.cpuUsage; //show the usage data on a textbox
Start_Click(null, EventArgs.Empty); //call this button again here
}
What I want to get look something like:
I think what you're looking for is the Timer
control. You can set it to run at a certain interval, and define the code that runs at that interval. You can also control the starting and stopping of the timer, if you want to only start it when a button is pressed.
For example, drop a Timer
control on your form and try out this code:
private void Form1_Load(object sender, EventArgs e)
{
// Set the interval to how often you want it to execute
timer1.Interval = (int)TimeSpan.FromSeconds(1).TotalMilliseconds;
// Set a method to run on every interval
timer1.Tick += Timer1_Tick;
}
public void Start_Click(object sender, EventArgs e)
{
// start or stop the timer
timer1.Enabled = !timer1.Enabled;
// Above we are just flipping the 'Enabled' property, but
// you could also call timer1.Start() (which is the same as
// setting 'Enabled = true') or timer1.Stop() (which is
// the same as setting 'Enabled = false')
}
// Put code in this method that should execute when the timer interval is reached
private void Timer1_Tick(object sender, EventArgs e)
{
var usage = new CpuUsage(); //placeholder class for getting the CPU use data
usage.setCPU(); //gets a random number
this.CPU.Text = usage.cpuUsage; //show the usage data on a textbox
}
User contributions licensed under CC BY-SA 3.0