gpt4 book ai didi

c# - 在C#中的线程中更改表单上的文本

转载 作者:行者123 更新时间:2023-12-03 13:20:56 25 4
gpt4 key购买 nike

我正在尝试将我的Form1文本框中的文本从一个线程中更改为“hello there”。
但是,当我执行它时,出现错误“对象引用未设置为对象的实例”。
当我检查时,我看到txtboxCheckedFiels具有Null值。

我将如何创建该txtbox的对象? (我有多个正在运行的线程,所有线程都应该能够更改该文本。

我尝试过的代码:

txtboxCheckedFiles.Invoke(new Action(() =>
{
txtboxCheckedFiles.Text = "Hello there";
}));

我尝试的另一种方式
var t = new Thread(
o =>
{
txtboxCheckedFiles.BeginInvoke(
((Action)(() => txtboxCheckedFiles.Text = "Hello there")));
});

最佳答案

首先,您必须检查是否需要调用,然后才能调用它。
另外,请考虑检查窗口是否有句柄,这意味着窗口已启动并正在运行(例如,如果您尝试在表单的构造函数中加载数据,则此操作将失败)

if (this.InvokeRequired)
{
IAsyncResult result = BeginInvoke(new MethodInvoker(delegate()
{
// DOSTUFF
}));

// wait until invocation is completed
EndInvoke(result);
}
else if (this.IsHandleCreated)
{
// DO STUFF
}

关于c# - 在C#中的线程中更改表单上的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12855191/

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