【问题标题】:$exception {Invoke or BeginInvoke cannot be called on a control until the window handle has been created.} System.InvalidOperationException$exception {在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。} System.InvalidOperationException
【发布时间】:2021-06-26 03:54:06
【问题描述】:

我创建了一个方法来编辑 WindowsForm 控件属性,例如文本框的文本。 但我在不同的类(不是 Form1 类)中创建此方法,此方法将由按钮单击处理程序调用,如下所示: 但我得到 [异常 {Invoke 或 BeginInvoke 不能在控件上调用,直到 ]

private void button1_Click(object sender, EventArgs e)
        {
            Update_UI Update_UI = new Update_UI();

            if (_client!=null )
            {
                _trigger = false;
                _StatusTxtBox.InvokeEx(stb => stb.Text += CRLF + " Server Disconnecting....");
                _client.Close();
                _listener.Stop();
            }
            else
            {
                Update_UI.UpdateUI("Update 02");
                //UpdateUI("Update_01");
            }
                
        }

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Server_app
{
   public class Update_UI
    {
        // To populate String:
        public void UpdateUI(string s)
        {
            
           Form1 f = new Form1();
            Func<int> fn = delegate ()
            {
              f._StatusTxtBox.AppendText(System.Environment.NewLine + s);
                return 0;
            };
            
                
                f._StatusTxtBox.Invoke(fn);

            
        }

    }
}

谢谢, 艾尔赛德

【问题讨论】:

  • 只是在这里仔细检查一下,但您知道UpdateUI 每次调用它时都会创建一个新的Form1,对吗?它不会对现有的 Form1 进行更改
  • 我不打算创建一个新的表单我只是想访问当前的表单,所以我认为这是问题所在,那么我如何从外部类访问当前的表单元素,例如在这里。
  • 你需要传递一个对它的引用。
  • 谢谢你,我按照你告诉我的做了,我通过引用传递了 Form1,就像开始工作一样。

标签: c#


【解决方案1】:

我在我的代码中这样做是为了将 Form1 作为 ref 参数传递给外部类 但是我怎样才能将另一个 windowsform 作为 ref 传递给这个类

 private void button1_Click(object sender, EventArgs e)
    {
        Form1 f = this as Form1;
        Update_UI_Frm1 Update_UI = new Update_UI_Frm1();

        if (_client!=null )
        {
            _trigger = false;
            _StatusTxtBox.InvokeEx(stb => stb.Text += CRLF + " Server is Disconnecting....");
            _client.Close();
            _listener.Stop();
        }
        else
        {
           
            Update_UI.UpdateUIFrm1(ref f,"Update 02");
            
        }
            
    }

public class Update_UI_Frm1
{
    // To populate String:
    public void UpdateUIFrm1(ref Form1 refform,string s)
    {
        Form1 Frm1 = refform;
        Func<int> fn = delegate ()
        {
          Frm1._StatusTxtBox.AppendText(System.Environment.NewLine + s);
            return 0;
        };
            Frm1._StatusTxtBox.Invoke(fn);
        
    }

}

}

【讨论】:

  • 请任何想法我如何通过引用特定类来传递多个窗口表单
猜你喜欢
  • 2010-10-22
  • 2021-05-14
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多