I have a program I wrote in C# with a window.
I have a button that do some things (it doesn't matter what exactly) and it refresh the window in his loop (in button_click function) (with this.Invalidate(false); (I don't use this.Refresh because I have a groupBox that I don't want to refresh)).
I cant minimize the window while the button_click function working. there is something I can do to solve it?
**lets say I have this code:
void button_click(object sender, EventArgs e)
{
progressBar1.Value = 0;
progressBar1.Maximum = int.Parse(somelabel_num.Text);
int i;
OpenFileDialog file = new OpenFileDialog();
file.ShowDialog();
if (file.FileName == "")
return;
this.Refresh();
Bitm开发者_Go百科ap image = new Bitmap(file.FileName);
groupBox1.BackgroundImage = image;
for (i = 0; i < int.Parse(somelabel_num.Text); i++)
{
this.Text = i;
this.Invalidate(false);
progressBar1.PerformStep();
}
}
so how to do this as a thread that gets the paremeters?
As already suggested, you should consider running button task in one of many ways you can in .NET (Thread, ThreadPool, Task etc).
However, if you are looking for a quick fix you can try one of these things:
Call Application.DoEvents() to allow UI to process window message pump. e.g.
WindowState = FormWindowState.Minimized; Application.DoEvents();
Call minimization asynchronously e.g.
if (InvokeRequired) BeginInvoke( new Action(() => WindowState = FormWindowState.Minimized) );
Better way is to run the code at your button in another thread so it will not block the UI when you press the button.
Edit: Code sample from my other answer:
private readonly object _userActivityLocker = new object();
private void button1_Click(object sender, EventArgs e)
{
new Thread(delegate()
{
if (System.Threading.Monitor.TryEnter(_userActivityLocker))
{
//note that any sub clicks will be ignored while we are here
try
{
//here execute your long running operation without blocking the UI
}
finally
{
System.Threading.Monitor.Exit(_userActivityLocker);
}
}
}) { IsBackground = true }.Start();
}
Edit: You stated at comment that
exception is occurs when the code reaches to an openFileDialog call). I get this exeption: System.Threading.ThreadStateException
You need to invoke the OpenFileDialog
code in the form main thread. so inside the try block:
this.Invoke(new Action(() =>
{
using (OpenFileDialog dialog = new OpenFileDialog())
{
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Console.WriteLine(dialog.FileName);
}
}
}));
Also check this.
Edit2: After seeing your question code updated, I will advice you to use BackgroundWorker instead.
精彩评论