如何在不同的线程上更改窗体的窗口状态?
有谁知道如何从另一个线程更改表单的窗口状态?这是我正在使用的代码:
private void button4_Click(object sender, EventArgs e)
{
string pathe = label1.Text;
string name = Path.GetFileName(pathe);
pathe = pathe.Replace(name, "");
string runpath = label2.Text;
Process process;
process = new Process();
process.EnableRaisingEvents = true;
process.Exited += new System.EventHandler(process_Exited);
process.StartInfo.FileName = @runpath;
process.StartInfo.WorkingDirectory = @pathe;
process.Start();
WindowState = FormWindowState.Minimized;
}
private void process_Exited(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
}
它的目的是运行一个程序并最小化,然后在程序关闭后返回到正常状态。尽管我收到此错误“跨线程操作无效:从创建它的线程以外的线程访问控制'Form1'”。知道如何让它发挥作用吗?
Does anyone know how I can change the window state of a form, from another thread? This is the code I'm using:
private void button4_Click(object sender, EventArgs e)
{
string pathe = label1.Text;
string name = Path.GetFileName(pathe);
pathe = pathe.Replace(name, "");
string runpath = label2.Text;
Process process;
process = new Process();
process.EnableRaisingEvents = true;
process.Exited += new System.EventHandler(process_Exited);
process.StartInfo.FileName = @runpath;
process.StartInfo.WorkingDirectory = @pathe;
process.Start();
WindowState = FormWindowState.Minimized;
}
private void process_Exited(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
}
It's meant to run a program and minimize, then return to the normal state once the program has closed. Although I get this error "Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on." Any idea how to get this to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这适用于 .NET 3.5:
或 2.0:
This will work in .NET 3.5:
Or 2.0:
只需在 StackOverflow“跨线程操作无效”或 Google 中搜索此字符串即可。拜托,别那么懒。
Just search this string in StackOverflow "Cross-thread operation not valid" or Google. Please, don't be that lazy.
请参阅 Invoke() 和 BeginInvoke() 之间的区别地点。 “选择的”答案很好地解释了你应该做什么。
长话短说,您想要不同的线程而不是完全创建一个新进程(或者您不太可能想要这样),并且您可能想要使用
Invoke()
而不是BeginInvoke()
这是异步的。See What’s the difference between Invoke() and BeginInvoke() on this site. The "chosen" answer gives a good explanation of what you're supposed to do.
Long story short, you want different THREADS not making a new process entirely (or highly unlikely you want that), and you probably want to use
Invoke()
and notBeginInvoke()
which is asynchronous.将此行代码添加到 Click 事件处理程序中:
Add this line of code to the Click event handler:
这将解决您的问题,将其添加到
form_load
事件中this will solve your problem add it in the
form_load
event