I am having a program.cs that is something like this :
namespace SumSwamp
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
But when I run the program it executes without any errors But the form1 is not being displayed. Please tell me if am doing something wrong
Here is my form class.
From your posted code, your error lies in this piece;
public static Boolean WaitForRoll = true;
public static int Turn = 0;
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(this.Form1_Load);
while(Turn == 0) //always true
{
if (WaitForRoll==false) //always false
{
//never reached code
DieTotal=DieLargeNum;
Random rnd1 = new Random();
DieLargeNum = rnd1.Next(1, 7);
if (DieTotal>DieLargeNum)
{
Turn = 1;
labelStatus.Text = "Player 1's Turn";
WaitForRoll=true;
}
else
{
Turn = 2;
labelStatus.Text = "Player 2's Turn";
WaitForRoll = false;
}
}
}
//...
}
Look at it closely and you will find that your code never leaves the first while loop, and thus the constructor never comes to an end resulting in the Form1 object never to be created.
Some tips;
Rethink your design. You should not place this code in your constructor, but in methods.
Read up on while loops. They are a pain if used incorrectly, which you did.
Your Form1 is not visible because there is an infinite loop in your code. Please check the following code it goes infinite.
while ((CompSum < TotalSpaces) & (PlayerSum < TotalSpaces))
{
...
}
Related
I'm separating out logic from one class to another in my Windows Form application. When all in one class, it works fine but I am moving the logic to it's own respective classes now. Having some issues getting at the backgroundWorker from a different class.
I have in class A
public partial class ClassA : Form
BackgroundWorker essentialBgWorker = new BackgroundWorker();
public ClassA()
{
InitializeComponent();
//essentialBgWorker
essentialBgWorker.DoWork += new DoWorkEventHandler(essentialBgWorker_DoWork);
essentialBgWorker.ProgressChanged += new ProgressChangedEventHandler(essentialBgWorker_ProgressChanged);
essentialBgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(essentialBgWorker_RunWorkerCompleted);
essentialBgWorker.WorkerReportsProgress = true;
}
That is a form that has a button which when clicked, copies files to another directory.
private void copyButton_Click(object sender, EventArgs e)
{
clickedButton = ((Button)sender).Name.ToString();
itemsChanged = ((Button)sender).Text.ToString();
essentialBgWorker.RunWorkerAsync();
}
This runs the background worker:
public void essentialBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
string buttonSender = clickedButton; //copyButton, deleteButton, etc.
switch (buttonSender)
{
case "copyButton":
//this is pseudocode - the important part being that this is where I would call the method from the other class
ClassB.copyDocuments();
break;
case "deleteButton":
//this is pseudocode - the important part being that this is where I would call the method from the other class
ClassB.deleteDocuments();
break;
default:
essentialBgWorker.CancelAsync();
break;
}
}
In my other class (ClassB) for this example I have the method that is called when the button is clicked (should be handling the logic).
public void copyDocuments()
{
ClassA classA = new ClassA();
//
//the logic that handles copying the files
//gets the filecount!
//Report to the background worker
int totalFileCount = fileCount;
int total = totalFileCount; //total things being transferred
for (int i = 0; i <= total; i++) //report those numbers
{
System.Threading.Thread.Sleep(100);
int percents = (i * 100) / total;
classA.essentialBgWorker.ReportProgress(percents, i);
//2 arguments:
//1. procenteges (from 0 t0 100) - i do a calcumation
//2. some current value!
}
//Do the copying here
}
I keep having an issue with this line:
classA.essentialBgWorker.ReportProgress(percents, i);
This line worked when it was in ClassA - but once bringing it into ClassB gives an error:
ClassA.essentialBgWorker' is inaccessible due to it's protection level
Just looking for some assistance on the proper way to get it to fire from the other class.
You must add public modifier to essentialBgWorker
public BackgroundWorker essentialBgWorker = new BackgroundWorker();
I am trying to update the progress bar as per the time taken by a function(which I wrote here in numerical terms) to be processed.But it only shows the last called value.
public static void updateProgress(int x)
{
Program.f.progressBar1.Visible = true;
Program.f.progressBar1.Enabled = true;
Program.f.progressBar1.Value +=x;
Thread.Sleep(5000);
}
above fn is used to update the progress bar.
public static Form1 f;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
f = new Form1();
f.progressBar1.Maximum = 100;
f.progressBar1.Minimum = 0;
f.progressBar1.Value = 0;
updateProgress(25); //fn1
updateProgress(50); //fn2
Application.Run(f);
}
The progressBar directly shows 75% progress.
Thanks
Wrong: you are doing something before form is displayed:
static void Main()
{
f = new Form1(); // form instance is created
f.progressBar1.Maximum = 100;
f.progressBar1.Minimum = 0;
f.progressBar1.Value = 0;
updateProgress(25); // you do something and change property
updateProgress(50); // you do something and change property
Application.Run(f); // here form is displayed and you see the most recent change
}
Correct: to simulate work, which run in background (while form is displayed) you can do something like:
static void Main()
{
f = new Form1(); // form instance is created
f.progressBar1.Maximum = 100;
f.progressBar1.Minimum = 0;
f.progressBar1.Value = 0;
// create and start task running in parallel
Task.Run(() =>
{
Thread.Sleep(3000); // wait long enough until form is displayed
updateProgress(25);
updateProgress(50);
});
Application.Run(f);
}
public static void updateProgress(int x)
{
// Invoke is required because we run it in another thread
f.Invoke((MethodInvoker)(() =>
{
Program.f.progressBar1.Visible = true;
Program.f.progressBar1.Enabled = true;
Program.f.progressBar1.Value +=x;
}));
Thread.Sleep(5000); // simulate work
}
It has been much already written about. But seems to me not clear.
I need to modify ProgressBar in WinForm according the calculus beeing provided in parallel flow. Code is below:
namespace my_space
{
class myLongCalculus
{
static int iCount;
doSomeLongJob()
{
cycle1
{
cycle2
{
iCount += number
// Here should be ProgressBar in Form1 modified !
}
}
}
public class Form1 : Form
{
public Form1()
{
int iMax = 6;
ProgressBar pb = new ProgressBar();
pb.Max = Maximum;
for(int i=0, i<iMax; i++)
listOfObjects.Add(new myLongCalculus(i));
Parallel.For(0, iMax, i =>
{
listOfObjects[i].doSomeLongJob();
});
}
}
}
I tried various tricks threads, invoke, but with the same result:
after the first changing of ProgressBar parallel flow terminates and returns to calling program.
Any ideas will be appreciated
I was creating playlist function for my own audio player application with NAudio Library, and completed source code. However, at Debugging, InvalidOperationException occured, and It says cross-thread occured exception.
So, I declared CheckForIllegalCrossThreadCalls = false on constructor of form. The exception doesn't occured, but program halts at specific line.
I didn't plan my application as multithreading application so any multithreading components are not used, or declared. but cross-thread exception occured, So I'm very embarrassing now.
This is a declaration and a constructor for frmMain :
AudioFileReader _audioFileReader;
IWavePlayer _waveOutDevice = new WaveOut();
static int nowIndex = 0;
static bool _paused = false;
static bool _manual_stop = false;
public frmMain()
{
InitializeComponent();
this.listMusic.DragOver += new DragEventHandler(this.FileDragOver);
this.listMusic.DragDrop += new DragEventHandler(this.FileDragDrop);
this.listMusic.DoubleClick += new EventHandler(this.listDoubleClick);
_waveOutDevice.PlaybackStopped += new EventHandler<StoppedEventArgs>(this.PlaybackStopped);
}
and Here's the point where cross-thread exception occured.
private void playMusic(int index)
{
if(_waveOutDevice.PlaybackState != PlaybackState.Stopped)
stopMusic();
_audioFileReader = new AudioFileReader(listMusic.Items[index].SubItems[0].Text); // Exception Occured
getProperties(listMusic.Items[index].Text);
_waveOutDevice.Init(_audioFileReader);
_waveOutDevice.Play();
btnPlayCtrl.Text = "II";
nowIndex = index;
_manual_stop = false;
}
...And, Here's halt point when I declared CheckForIllegalCrossThreadCalls = false
_waveOutDevice.Init(_audioFileReader); //from foregone source code.
It just make application halt, However, It didn't occur any exceptions and pause debugging. when i paused the debugging for analyze it, but debugger pointed here.
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length > 0)
Application.Run(new frmMain(args[1]));
else
Application.Run(new frmMain());
} // Debugger Points Here
Remove the CheckForIllegalCrossThreadCalls = false; line in your constructor...
Then try moving execution back to the main UI thread like this:
private void playMusic(int index)
{
this.Invoke((MethodInvoker)delegate
{
if (_waveOutDevice.PlaybackState != PlaybackState.Stopped)
stopMusic();
_audioFileReader = new AudioFileReader(listMusic.Items[index].SubItems[0].Text);
_waveOutDevice.Init(_audioFileReader);
_waveOutDevice.Play();
btnPlayCtrl.Text = "II";
nowIndex = index;
_manual_stop = false;
});
}
I'm having a problem while trying to switch between a group of photos in a Form(1).
I'm using picturebox.Image in order to view the chosen picture, and after certain time interval (let's say 4Sec) , switch to a random photo in the same group of photos.
While switching between each photo, i would like to show another Form(2) for 1Sec, and then go back to Form(1).
my Code in Form(1):
public partial class Form1: Form
{
public static Timer time;
public static Form mod;
public Form1()
{
InitializeComponent();
time = new Timer();
mod = new Form2();
mod.Owner = this;
mod.Show();
this.Hide();
RunForm1();
}
public void RunForm1()
{
for (int i = 0; i < groupSize; i++)
{
mod.Owner = this;
mod.Show();
this.Hide();
}
}
}
my Code in Form(2):
public partial class Form2: Form
{
public static Timer time;
public int index = -1;
public List<Image> images;
public DirectoryInfo dI;
public FileInfo[] fileInfos;
public Form2()
{
InitializeComponent();
images = new List<Image>();
time = new Timer();
dI = new DirectoryInfo(#"C:\Users\Documents\Pictures");
fileInfos = dI.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
foreach (FileInfo fi in fileInfos)
images.Add(Image.FromFile(fi.FullName));
index = images.Count;
time.Start();
RunForm2();
}
public void RunForm2()
{
Random rand = new Random();
int randomCluster = rand.Next(0, 1);
while (index != 0)
{
pictureBox1.Image = images[Math.Abs(index * randomCluster)];
setTimer();
index--;
}
}
public void setTimer()
{
if (time.Interval == 4000)
{
this.Owner.Show();
this.Close();
}
}
}
My main problems in this code is:
1. The time is not updating, i mean, time.Interval is always set to 100
2. i dont know why, but, the photos, never shows in the picturebox.Image although, in debug mode it shows that the photos are being selected as properly.
Thank you for you help!
Roy.
You need to use the Tick event from the timer to know when the time has elapsed.
you check if the interval equals (==) 4000, but you need to set it to 4000 (time.Interval = 4000) and then start the timer. Then the Tick event will fire after 4 seconds.
And the problem of the image not being showed could be solved by calling pictureBox1.UpdateLayout();