gpt4 book ai didi

c# - 使用表单和类进行线程化

转载 作者:行者123 更新时间:2023-11-30 18:31:45 25 4
gpt4 key购买 nike

我编写了一个程序来设计网络浏览器。我将我的代码组织成类。其实我有几个问题...

第一个问题:

为了访问表单元素,我在类里面使用了这个语句:

Form1 fc = (Form1)Application.OpenForms["form1"];

当我调用我使用的元素时:

fc.listboxObject.SelectedItem;

我不知道这是不是正确的方法,因为当我使用

`Form1 f=new Form1();`

它会创建新的表单,不会更新原来的表单。我将表单中的所有元素设置为公开。

第二个问题在表单中,我必须使用线程创建新的网页窗口,以便用户可以在不同的窗口中请求多个网页。

    public void start_new_page()
{
Form1 f = new Form1();
Application.Run(f);

}

private void new_page_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(start_new_page));
t.Start();

}

单击按钮时出现以下错误:跨线程操作无效:从创建它的线程以外的线程访问控件“listboxObject”。

我搜索了很多使用 invoke 找到的解决方案,但我不想使用它,因为它只会更新原始表单。我想让每个表单彼此分开但共享相同的历史列表和收藏夹列表。另外,我不能使用 Backgroundworker。下面的代码是其中一个类的方法之一,我在这里出错了。实际上,在类中的所有方法中,我都遇到了这个错误。

    public void printlistbox(string textname)
{
Form1 fc = (Form1)Application.OpenForms["form1"];
int count = 0;
string line1;
System.IO.StreamReader file1 = new System.IO.StreamReader(textname);
fc.listboxObject.Items.Clear();
while ((line1 = file1.ReadLine()) != null)
{
string[] split = line1.Split(new Char[] { '\t' });
count = 0;
foreach (string s in split)
{

if (count == 1)
fc.listboxObject.Items.Add(s);
count += 1;
}
}
file1.Close();

当点击打印按钮时,会调用printlistbox函数。

最佳答案

当调用 'new Form()' 时,你的应用程序在主线程上创建一些元素,当在单独的线程上调用它时,你可以创建一个交叉操作尝试这样做

   public void start_new_page()
{
Dispatcher.Invoke(
(Action)delegate()
{
Form1 f = new Form1();
Application.Run(f);
}, System.Windows.Threading.DispatcherPriority.Normal);
}

关于c# - 使用表单和类进行线程化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19566188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com