Im getting a stackoverflow exception when i'm filling the ellipse not just one ellipse but many ellipses.
I dont think it is a problem from the graphics creator. But i can't figure out why the debugger is pointing a stackoverflow exception at the FillEllipse command
public void createPath(Stance currentStance)
{
if(toSort.Count > 0)
{
toSort.Remove(currentStance);
counter++;
}
this.currentForm.FillEllipse(new SolidBrush(Color.Red),new Rectangle(currentStance.location.X-3, currentStance.location.Y - 3, 6 , 6));
foreach(Stance subStance in currentStance.childStances)
{
double weight = level(currentStance, subStance, 1)+ currentStance.StanceWeight;
if (subStance.StanceWeight == -99999999999999)
{
currentStance.dajkstrasChildren.Add(subStance);
subStance.parentStance = currentStance;
subStance.StanceWeight = weight;
toSort.Add(subStance);
}
else
{
if(weight > subStance.StanceWeight)
{
try
{
subStance.parentStance.dajkstrasChildren.Remove(subStance);
}
catch (NullReferenceException e)
{
Console.WriteLine("null reference");
}
subStance.parentStance = currentStance;
currentStance.dajkstrasChildren.Add(subStance);
subStance.StanceWeight = weight;
}
}
}
foreach(Stance subStance in currentStance.secondChildStances)
{
double weight = level(currentStance, subStance, 1) + currentStance.StanceWeight;
if (subStance.StanceWeight == -99999999999999)
{
currentStance.dajkstrasChildren.Add(subStance);
subStance.parentStance = currentStance;
toSort.Add(subStance);
subStance.StanceWeight = weight;
}
else
{
if (weight > subStance.StanceWeight)
{
if(subStance.parentStance != null)
{
try
{
subStance.parentStance.dajkstrasChildren.Remove(subStance);
subStance.parentStance = currentStance;
currentStance.dajkstrasChildren.Add(subStance);
}
catch(NullReferenceException e)
{
Console.WriteLine("null reference");
}
}
}
}
}
toSort.Sort(new Stance());
if(toSort.Count != 0)
{
createPath((Stance)toSort[0]);
}
}
it is a recursive method but it cant recurse to infinity as it always pops a single object from the toSort ArrayList
That's because it is in the attempt to make the call to FillEllipse that the stack actually runs out.
Of course the stack overflow has to be caused by a flaw in your logic that causes your createPath method to be called recursively either (probably) indefinitely or too deeply for the stack to accommodate all the needed activation frames.
Use a while loop instead of recursion to avoid loading up the stack.
Here is your code modified that might work:
public void createPath(Stance stance)
{
var currentStance = stance;
while(toSort.Count >0)
{
toSort.Remove(currentStance);
counter++;
this.currentForm.FillEllipse(new SolidBrush(Color.Red),new Rectangle(currentStance.location.X-3, currentStance.location.Y - 3, 6 , 6));
foreach(Stance subStance in currentStance.childStances)
{
double weight = level(currentStance, subStance, 1)+ currentStance.StanceWeight;
if (subStance.StanceWeight == -99999999999999)
{
currentStance.dajkstrasChildren.Add(subStance);
subStance.parentStance = currentStance;
subStance.StanceWeight = weight;
toSort.Add(subStance);
}
else
{
if(weight > subStance.StanceWeight)
{
try
{
subStance.parentStance.dajkstrasChildren.Remove(subStance);
}
catch (NullReferenceException e)
{
Console.WriteLine("null reference");
}
subStance.parentStance = currentStance;
currentStance.dajkstrasChildren.Add(subStance);
subStance.StanceWeight = weight;
}
}
}
foreach(Stance subStance in currentStance.secondChildStances)
{
double weight = level(currentStance, subStance, 1) + currentStance.StanceWeight;
if (subStance.StanceWeight == -99999999999999)
{
currentStance.dajkstrasChildren.Add(subStance);
subStance.parentStance = currentStance;
toSort.Add(subStance);
subStance.StanceWeight = weight;
}
else
{
if (weight > subStance.StanceWeight)
{
if(subStance.parentStance != null)
{
try
{
subStance.parentStance.dajkstrasChildren.Remove(subStance);
subStance.parentStance = currentStance;
currentStance.dajkstrasChildren.Add(subStance);
}
catch(NullReferenceException e)
{
Console.WriteLine("null reference");
}
}
}
}
}
toSort.Sort(new Stance());
currentStance = (Stance)toSort[0];
}
}
Related
I want realize arithmetic operations with my list, in this case:
Column "width" * Column "height" should re-Write the Column "Partial".
I have tried do a loop but It is not working.
I put a breakPoint at the row:
_Area[i].Partial = _Area[i].width * _Area[i].height;
And the debug never stop them I can think this line is not been readed.
This is my Collection View Model:
public class CollectionVM_Area : BindableBase
{
private Values_Area _Area = new Values_Area();
public Values_Area Area
{
get { return _Area; }
set { SetProperty(ref _Area, value); }
}
public CollectionVM_Area()
{
_Area.Add(new Area()
{
width=10,
height=11,
});
_Area.Add(new Area()
{
width=5,
height=5,
Partial=1,
});
bool NeedPartial = false;
int i = 0;
while (NeedPartial = false && i < _Area.Count)
{
if (_Area[i].Partida == true)
{
NeedPartial = true;
}
else
{
i++;
}
}
if (NeedPartial==true)
{
_Area[i].Partial = _Area[i].width * _Area[i].height;
NeedPartial = false;
}
else
{
NeedPartial = true;
}
}
}
My Project is a UWP but I think is no different in with a windows forms in lists, any help is appreciated.
You have two mistalkes in your code. First your while-loop makes an assignement instead of a comparisson (= towards ==). Thus the first term within your while-condition allways evaluates to false. Secondly your calculation is located outside the loop causing the NeedPartial-value to be set but not never be read which I doubt is what you want.
Write this therefor:
bool NeedPartial = false;
int i = 0;
while (NeedPartial == false && i < _Area.Count) // or even simpler: while (!NeedPartial ...)
{
if (_Area[i].Partida == true) // or simply: if (_Area[i].Partida) { ... }
{
NeedPartial = true;
}
else
{
i++;
}
if (NeedPartial==true) // if (NeedPartial) ...
{
_Area[i].Partial = _Area[i].width * _Area[i].height;
NeedPartial = false;
}
else
{
NeedPartial = true;
}
}
Edit: Answered.
The Correct Loop is:
bool NeedPartial = false;
int i = 0;
while (!NeedPartial && i < _Area.Count)
{
if (_Area[i].Partida)
{
NeedPartial = true;
}
else
{
i++;
}
if (NeedPartial)
{
_Area[i].Partial = _Area[i].width * _Area[i].height;
NeedPartial = false;
i++;
}
else
{
NeedPartial = true;
}
}
Thanks to HimBromBeere for your help.
i have a form with more than one NumericUpDown as controls to input answer. i want every input is true for an operation (multiplication, sum etc), NumericUpDown for that operation will be disable. i have used the code below (just for sum operation), but i think its not efficient because i have to make a method to check every operation.
private void IsSumTrue() {
if (add1 + add2 == sum.Value)
{
sum.Enabled = false;
}
}
private void IsDifferenceTrue()
{
if (add1 - add2 == difference.Value)
{
difference.Enabled = false;
}
}
private void IsProductTrue()
{
if (add1 * add2 == product.Value)
{
product.Enabled = false;
}
}
private void IsQuotientTrue()
{
if (add1 / add2 == quotient.Value)
{
quotient.Enabled = false;
}
}
anyone have idea how to make it more efficient with just a method for all operation?
below is my idea, but to check the value is true for every NumericUpDown i don't know how.
private void DisableIfValueIsTrue()
{
foreach(Control control in this.Controls)
{
NumericUpDown value = control as NumericUpDown;
// if(value [NEED HELP]
}
}
Considering your situtaion, you can set a tag for each NumericUpDown in design mode like this:
sum.Tag=1;
square.Tag=2;
etc
Then define some int variables:
int iSum=add1+add2;
int iSquare= //Whatever you want
etc
And finally loop through your controls this way:
foreach (NumericUpDown control in this.Controls.OfType<NumericUpDown>())
{
int intCondition = Convert.ToInt32(control.Tag) == 1
? iSum
: Convert.ToInt32(control.Tag) == 2
? iSquare
: Convert.ToInt32(control.Tag) == 3
? i3
: i4; //You should extend this for your 8 controls
control.Enabled = intCondition == control.Value;
}
OK! Second way I offer
Since you will have to always check 8 different conditions, you could simply forget about looping through the controls and just change your method like this:
private void DisableIfValueIsTrue()
{
sum.Enabled = add1 + add2 != sum.Value;
difference.Enabled= add1 - add2 != difference.Value;
product.Enabled= add1 * add2 != product.Value;
quotient.Enabled= (add2 !=0) && (add1 / add2 != quotient.Value);
//etc
}
I came across this while doing some research and would like to give my solution I used for my situation and hope it helps people. I needed minimum and maximum numbers for a calculation, so mine are named appropriately and I correlated these with some CheckBoxes. I used null in beginning of minimum and end of maximum to account for empty. I also had to create an event handler SubscribeToEvents() shown below.
In my load event for my form:
SubscribeToEvents();
_checkBoxs = new[] { cbXLight, cbLight, cbMedium, cbHeavy, cbXHeavy, cbXXHeavy, cbXXXHeavy };
_minimumsNumericUpDowns = new[] { null, nLightMin, nMediumMin, nHeavyMin, nXHeavyMin, nXXHeavyMin, nXXXHeavyMin };
_maximumsNumericUpDowns = new[] { nXLightMax, nLightMax, nMediumMax, nHeavyMax, nXHeavyMax, nXXHeavyMax, null };
then I created a method:
private void DisableNumericUpDowns()
{
// disable everything:
foreach (var n in _minimumsNumericUpDowns)
{
if (n != null)
n.Enabled = false;
}
foreach (var n in _maximumsNumericUpDowns)
{
if (n != null)
n.Enabled = false;
}
}
The event handler:
private bool _eventsSubscribed;
private void SubscribeToEvents()
{
if (_eventsSubscribed)
return;
_eventsSubscribed = true;
cbXXHeavy.CheckedChanged += CheckBox_NumericState;
cbXHeavy.CheckedChanged += CheckBox_NumericState;
cbXLight.CheckedChanged += CheckBox_NumericState;
cbHeavy.CheckedChanged += CheckBox_NumericState;
cbLight.CheckedChanged += CheckBox_NumericState;
cbMedium.CheckedChanged += CheckBox_NumericState;
cbXXXHeavy.CheckedChanged += CheckBox_NumericState;
}
Now I can used this to check when they are enabled and if they are greater than or less than 0 if needed in the method CheckBox:
private void CheckBox_NumericState(object sender, EventArgs e)
{
// disable everything
DisableNumericUpDowns();
// see if more than one checkbox is checked:
var numChecked = _checkBoxs.Count((cb) => cb.Checked);
// enable things if more than one item is checked:
if (numChecked <= 1) return;
// find the smallest and enable its max:
var smallest = -1;
for (var i = 0; i < _checkBoxs.Length; i++)
{
if (!_checkBoxs[i].Checked) continue;
if (_maximumsNumericUpDowns[i] != null)
{
_maximumsNumericUpDowns[i].Enabled = true;
}
smallest = i;
break;
}
// find the largest and enable its min:
var largest = -1;
for (var i = _checkBoxs.Length - 1; i >= 0; i--)
{
if (!_checkBoxs[i].Checked) continue;
if (_minimumsNumericUpDowns[i] != null)
{
_minimumsNumericUpDowns[i].Enabled = true;
}
largest = i;
break;
}
// enable both for everything between smallest and largest:
var tempVar = largest - 1;
for (var i = (smallest + 1); i <= tempVar; i++)
{
if (!_checkBoxs[i].Checked) continue;
if (_minimumsNumericUpDowns[i] != null)
{
_minimumsNumericUpDowns[i].Enabled = true;
}
if (_maximumsNumericUpDowns[i] != null)
{
_maximumsNumericUpDowns[i].Enabled = true;
}
}
}
So I can check each state as required:
I want to check if Extra Light is check:
// Extra Light
if (!cbXLight.Checked) return;
if (nXLightMax.Enabled == false)
{
_structCategoryType = XLight;
CheckStructureSheets();
}
else
{
if (nXLightMax.Value > 0)
{
_dMax = nXLightMax.Value;
_structCategoryType = XLight;
CheckStructureSheets();
}
else
{
MessageBox.Show(#"Extra Light Max cannot be zero (0)");
}
}
and next light checks both:
// Light
if (cbLight.Checked)
{
if (nLightMin.Enabled == false && nLightMax.Enabled == false)
{
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
if (nLightMin.Enabled && nLightMin.Value > 0)
{
if (nXLightMax.Enabled && nLightMin.Enabled && nLightMax.Enabled == false)
{
_dMin = nLightMin.Value;
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
if (nLightMax.Value > 0)
{
_dMin = nLightMin.Value;
_dMax = nLightMax.Value;
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
MessageBox.Show(#"Light Max cannot be zero (0)");
return;
}
}
}
else if (nLightMin.Enabled == false && nLightMax.Enabled)
{
if (nLightMax.Value > 0)
{
_dMax = nLightMax.Value;
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
MessageBox.Show(#"Light Max cannot be zero (0)");
}
}
else
{
MessageBox.Show(#"Light Min cannot be zero (0)");
return;
}
}
}
Hope this helps someone.
Tim
thanks for #AlexJoliq and #BrettCaswell. just want to inform that before Alex edited his answer from using "==" to "!=", i (thought) already solved the problem. but i don't know where is the more effective and efficient way, alex's or mine.
below is my code for DisableIfValueIsTrue():
if (add1 + add2 == sum.Value) sum.Enabled = false;
if (add1 - add2 == difference.Value) difference.Enabled = false;
if (add1 * add2 == product.Value) product.Enabled = false;
if (add1 / add2 == quotient.Value) quotient.Enabled = false;
Hi guys I have such construction:
Start threads:
Thread[] thr;
int good_auth, bad_auth, good_like, bad_like;
static object accslocker = new object();
static object limitlocker = new object();
string acc_path, proxy_path, posts_path;
int position_of_limit, position = 0;
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
decimal value = numericUpDown1.Value;
int i = 0;
int j = (int)(value);
thr = new Thread[j];
for (; i < j; i++)
{
thr[i] = new Thread(new ThreadStart(go));
thr[i].IsBackground = true;
thr[i].Start();
}
}
And than function go:
public void go()
{
while (true)
{
string acc = "";
string proxy = "";
lock (limitlocker)
{
if (position_of_limit >= int.Parse(textBox2.Text) - 1)
{
position_of_limit = 0;
if (position < posts.Count - 1)
position++;
else
{
break;
}
}
}
lock (accslocker)
{
if (accs.Count == 0)
{
break;
}
else
acc = accs.Dequeue();
}
OD od = new OD(acc);
string login = od.Auth();
if (login == "Login")
{
lock (accslocker)
{
good_auth++;
log_good_auth(good_auth);
}
string like = od.like(posts[position], textBox1.Text);
if (like == "Good")
{
lock (accslocker)
{
position_of_limit++;
good_like++;
log_good_like(good_like);
}
}
else if (like == "Failed")
{
lock (accslocker)
{
bad_like++;
log_bad_like(bad_like);
}
}
else
{
lock (accslocker)
{
bad_like++;
log_bad_like(bad_like);
}
}
}
else if (login == "Spamblock")
{
lock (accslocker)
{
bad_auth++;
log_bad_auth(bad_auth);
}
}
else if (login == "Locked")
{
lock (accslocker)
{
bad_auth++;
log_bad_auth(bad_auth);
}
}
else if (login == "Invalid")
{
lock (accslocker)
{
bad_auth++;
log_bad_auth(bad_auth);
}
}
else if (login == "Bad_proxy")
{
lock (accslocker)
{
accs.Enqueue(acc);
Proxy.proxies.Remove(proxy);
}
}
else
{
lock (accslocker)
{
accs.Enqueue(acc);
Proxy.proxies.Remove(proxy);
}
}
}
}
I start for example 20 threads, when position_of_limit becomes bigger than int.Parse(textBox2.Text) - 1 all threads need to take next posts[position] in next loop. But I receive an exception on line string like = od.like(posts[position], textBox1.Text);
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
How to solve this problem? Thanks
Locking the GUI thread is evil, since it's an STA thread.
That means it must manage a message loop and is not allowed to block. So blocking is likely to cause deadlocks.
Rather use callbacks like BackgroundWorker.RunWorkerCompleted.
Some other informative links about locking:
Guidelines of when to use locking
Obtaining lock on a UI thread
I am working on a Reverse polish notation calculator. I created a method that will take care of the calculations but there are three lines in my code that are causing an error. After every = an operation is performed and then displayed. I am trying to grab the string from TxtInputBox and convert to integers but it always shows the catch message Please check the input. Then nothing gets calculated or display. I am sure that my first if statement will check for actual integers and avoid the characters. My ultimate goal is to input a formula in rpn format and have the result display in the multiline textbox.
Sample Input 5 6 -=
Code
namespace rpncalc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void RPNCalc(TextBox TxtBoxInputbox, TextBox TxtBoxOutputbox)
{
Stack<int> stackone = new Stack<int>();
stackone.Clear();
string[] inputarray = TxtBoxInputbox.Text.Split();
int end = inputarray.Length - 1;
int numinput;
int i = 0;
do
{
if(inputarray[i] != "=" && inputarray[i] != "+" && inputarray[i] != "-" && inputarray[i] != "*" && inputarray[i] != "/")
{
try
{
numinput = Convert.ToInt32(inputarray[i]);
stackone.Push(numinput);
}
catch
{
MessageBox.Show("Please check the input");
}
}
else if (inputarray[i]== "+")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "-")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "+")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "*")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "/")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
}
while(i < end && inputarray[i]!= "=" && stackone.Count != 0);
string txtout = TxtInputBox + " " + stackone.Pop().ToString() + Environment.NewLine;
TxtOutputBox.AppendText(txtout);
TxtInputBox.Clear();
}
private void Btn_Calc_Click(object sender, EventArgs e)
{
RPNCalc(TxtInputBox, TxtOutputBox);
}
}
}
The Split command, with no argument, is splitting the string on spaces and other whitespace.
There is no space in the input between -= so it is treated as one token that doesn't match the tests in the if statement.
Original answer incorrectly suggested that Split with no argument was splitting into individual characters.
What are you doing to increment i after each iteration of your do loop? I tried out your code and it seems like i is never incremented. Also, when you catch and run
catch
{
MessageBox.Show("Please check the input");
}
You could perhaps change it to:
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
so you could be sure of just what you're catching, and why.
Edit:
Here's my version of your code, now working correctly:
i is incremented in each iteration
Fixed the typo in the minus, multiplication and division operators that made them do addition instead
Removed the redundant addition operator
namespace rpncalc {
public partial class Form1 : Form {
public Form1 () {
InitializeComponent();
}
private void RPNCalc (TextBox TxtBoxInputbox, TextBox TxtBoxOutputbox) {
Stack<int> stackone = new Stack<int>();
stackone.Clear();
string[] inputarray = TxtBoxInputbox.Text.Split();
int end = inputarray.Length - 1;
int numinput;
int i = 0;
do {
if (inputarray[i] != "=" && inputarray[i] != "+" && inputarray[i] != "-" && inputarray[i] != "*" && inputarray[i] != "/") {
try {
numinput = Convert.ToInt32(inputarray[i]);
stackone.Push(numinput);
} catch (Exception e) {
MessageBox.Show(e.ToString());
}
} else if (inputarray[i] == "+") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
} catch {
}
} else if (inputarray[i] == "-") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 - store1);
} catch {
}
} else if (inputarray[i] == "*") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 * store1);
} catch {
}
} else if (inputarray[i] == "/") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 / store1);
} catch {
}
}
}
while (i++ < end && inputarray[i] != "=" && stackone.Count != 0);
string txtout = TxtInputBox.Text + " " + stackone.Pop().ToString() + Environment.NewLine;
TxtOutputBox.AppendText(txtout);
TxtInputBox.Clear();
}
private void Btn_Calc_Click (object sender, EventArgs e) {
RPNCalc(TxtInputBox, TxtOutputBox);
}
}
}
I read somewhere that i need to dispose objects when closing the application ?
I have this properties i did to use them in tow functions i needed to invoke them since im using a backgroundworker.
In most of the times when i closed my application it was ok but now i got this exception.
private string CpuTextLabelProperty
{
set
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => CpuTemperature_label.Text = value), null);
}
}
get
{
return CpuTemperature_label.Text;
}
}
private Point CpuLocationLabelProperty
{
set
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => CpuTemperature_label.Location = new Point(210, 200)), null);
}
}
get
{
return CpuTemperature_label.Location;
}
}
private string GpuTextLabelProperty
{
set
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => GpuTemperature_label.Text = value), null);
}
}
get
{
return GpuTemperature_label.Text;
}
}
private Point GpuLocationLabelProperty
{
set
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => GpuTemperature_label.Location= new Point(210,100)), null);
}
}
get
{
return GpuTemperature_label.Location;
}
}
private string Label4TextProperty
{
set
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => label4.Text = value), null);
}
}
}
The exception is on the property: GpuTextLabelProperty inside the get on the line:
return GpuTemperature_label.Text;
Win32Exception - Error creating window handle
My Form1 closing event:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
this.BeginInvoke((MethodInvoker)delegate { this.Close(); });
}
}
If i need ot dispose something wich ones ? And how ?
This is the functions im using the properties:
private void cpuView()
{
Computer myComputer = new Computer();
myComputer = new Computer(settings) { CPUEnabled = true };
myComputer.Open();
Trace.WriteLine("");
foreach (var hardwareItem in myComputer.Hardware)
{
if (hardwareItem.HardwareType == HardwareType.CPU)
{
hardwareItem.Update();
foreach (IHardware subHardware in hardwareItem.SubHardware)
subHardware.Update();
foreach (var sensor in hardwareItem.Sensors)
{
settings.SetValue("sensor", sensor.Value.ToString());
if (sensor.SensorType == SensorType.Temperature)
{
sensor.Hardware.Update();
settings.GetValue("sensor", sensor.Value.ToString());
int t = CpuTextLabelProperty.Length;
if (t >= 4)
{
CpuLocationLabelProperty = new Point(210, 200); // not working to check everything about the locations \\
}
else
{
CpuLocationLabelProperty = new Point(250, 200);
}
CpuTextLabelProperty = sensor.Value.ToString() + "c";//String.Format("{0} Temperature = {1}c", sensor.Name, sensor.Value.HasValue ? sensor.Value.Value.ToString() : "no value");
tempCpuValue = sensor.Value;
break;
}
}
}
}
}
private void gpuView()
{
Computer computer = new Computer();
computer.Open();
computer.GPUEnabled = true;
foreach (var hardwareItem in computer.Hardware)
{
if (videoCardType("ati", "nvidia") == true)
{
HardwareType htype = HardwareType.GpuNvidia;
if (hardwareItem.HardwareType == htype)
{
foreach (var sensor in hardwareItem.Sensors)
{
if (sensor.SensorType == SensorType.Temperature)
{
sensor.Hardware.Update();
if (sensor.Value.ToString().Length > 0)
{
if (GpuTextLabelProperty.Length < 1)
{
if (UpdatingLabel(sensor.Value.ToString(), string.Empty))
{
// Label8 = GpuText;
}
}
else if (UpdatingLabel(sensor.Value.ToString(), GpuTextLabelProperty.Substring(0, GpuTextLabelProperty.Length - 1)))
{
// Label8 = GpuText;
}
GpuTextLabelProperty = sensor.Value.ToString() + "c";
tempGpuValue = sensor.Value;
//label8.Visible = true;
}
int t = GpuTextLabelProperty.Length;
if (t >= 4)
{
GpuLocationLabelProperty = new Point(210, 100);
}
else
{
GpuLocationLabelProperty = new Point(250, 100);
}
// timer2.Interval = 1000;
if (sensor.Value > 90)
{
Logger.Write("The current temperature is ===> " + sensor.Value);
button1.Enabled = true;
}
//this.Select();
}
}
}
}
else
{
HardwareType htype = HardwareType.GpuAti;
if (hardwareItem.HardwareType == htype)
{
foreach (var sensor in hardwareItem.Sensors)
{
if (sensor.SensorType == SensorType.Temperature)
{
sensor.Hardware.Update();
if (sensor.Value.ToString().Length > 0)
{
if (GpuTextLabelProperty.Length < 1)
{
if (UpdatingLabel(sensor.Value.ToString(), string.Empty))
{
// Label8 = GpuText;
}
}
else if (UpdatingLabel(sensor.Value.ToString(), GpuTextLabelProperty.Substring(0, GpuTextLabelProperty.Length - 1)))
{
// Label8 = GpuText;
}
GpuTextLabelProperty = sensor.Value.ToString() + "c";
tempGpuValue = sensor.Value;
//label8.Visible = true;
}
int t = GpuTextLabelProperty.Length;
if (t >= 4)
{
GpuLocationLabelProperty = new Point(210, 100);
}
else
{
GpuLocationLabelProperty = new Point(250, 100);
}
//timer2.Interval = 1000;
if (sensor.Value > 90)
{
Logger.Write("The current temperature is ===> " + sensor.Value);
button1.Enabled = true;
}
this.Select();
}
}
}
}
}
}
And this is the full exception message:
System.ComponentModel.Win32Exception was unhandled by user code
Message=Error creating window handle.
Source=System.Windows.Forms
ErrorCode=-2147467259
NativeErrorCode=87
StackTrace:
at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.get_WindowText()
at System.Windows.Forms.Control.get_Text()
at System.Windows.Forms.Label.get_Text()
at HardwareMonitoring.Form1.get_GpuTextLabelProperty() in D:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 613
at HardwareMonitoring.Form1.gpuView() in D:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 412
at HardwareMonitoring.Form1.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\C-Sharp\HardwareMonitoring\HardwareMonitoring\Hardwaremonitoring\Form1.cs:line 670
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException:
You have to stop your background worker when you close or exit your application. The exceptions gets thrown at you because the objects your code is relying on are being torn down by the OS.
See this thread on how to do it.