Windows 窗体
一组用于开发图形用户界面的 .NET Framework 托管库。
113 个问题
在网络连接或断开连接后更改 Windows 状态会引发错误
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.'
附上源代码。 请只做那些需要的。
using iTuner;
using System;
using System.Windows.Forms;
namespace NetworkConnectError
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DisposeBrowser();
WindowState = FormWindowState.Minimized;
this.Visible = false;
}
private void DisposeBrowser()
{
try
{
if (webBrowser1 == null || webBrowser1.IsDisposed) return;
webBrowser1.Navigate(new Uri("about:blank"));//TRK - 107
webBrowser1.Stop();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void NetworkAvailabilityChanged(object sender, NetworkStatusChangedArgs e)
{
try
{
if (e.IsAvailable)
{
System.Threading.Thread myThread = new System.Threading.Thread(new System.Threading.ThreadStart(Client));
myThread.Start();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Client()
{
WindowState = FormWindowState.Maximized;
webBrowser1.Left = 0;
webBrowser1.Top = 0;
Screen scr = Screen.PrimaryScreen;
webBrowser1.Width = scr.Bounds.Width;
int iHeight = scr.Bounds.Height;
iHeight = iHeight + 50;
webBrowser1.Height = iHeight;
}
private void Form1_Load(object sender, EventArgs e)
{
NetworkStatus.AvailabilityChanged += new NetworkStatusChangedHandler(NetworkAvailabilityChanged);
}
}
}
如Castorix31 说,您需要从线程安全地调用 Windows 窗体控件。
我使用 BackgroundWorker 而不是您的线程。
以下是我修改后的代码:
private void NetworkAvailabilityChanged(object sender, NetworkStatusChangedArgs e)
{
try
{
if (e.IsAvailable)
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);
backgroundWorker.RunWorkerAsync();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
NetworkStatus.AvailabilityChanged += new NetworkStatusChangedHandler(NetworkAvailabilityChanged);
}
private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
webBrowser1.Left = 0;
webBrowser1.Top = 0;
Screen scr = Screen.PrimaryScreen;
webBrowser1.Width = scr.Bounds.Width;
int iHeight = scr.Bounds.Height;
iHeight = iHeight + 50;
webBrowser1.Height = iHeight;
}
如果回复有帮助,请单击“接受答案”并投赞成票。 注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。