繁体   English   中英

如何从C#中相同表单内的方法访问表单控件?

[英]How to access form control from a method within same form in C#?

我的服务器表单接受来自客户端的连接请求,然后我需要在名为lstIP的列表框中添加已连接客户端的IP地址。但是我无法从OnClientConnect方法访问lstIP.help将不胜感激。以下是代码:

public partial class Form1 : Form
    {
        public int cpuLoad;
        private PerformanceCounter cpuCounter;
      static  public string curIP;
       public static string get_localip = GetLocalIP();

        public Form1()
        {
            InitializeComponent();
            InitialiseCPUCounter();
            timer1.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lblServerIP.Text += " "+get_localip;
        }
          private static TcpListener _listener;

           public static void StartServer() 
    {
         System.Net.IPAddress localIPAddress = System.Net.IPAddress.Parse(get_localip);
        IPEndPoint ipLocal = new IPEndPoint(localIPAddress, 8888);
        _listener = new TcpListener(ipLocal);
        _listener.Start();
        WaitForClientConnect();

    }
    private static void WaitForClientConnect()
    {
        object obj = new object();
        _listener.BeginAcceptTcpClient(new System.AsyncCallback(OnClientConnect), obj);
    }
    public static void OnClientConnect(IAsyncResult asyn)
    {
        try
        {

            TcpClient clientSocket = default(TcpClient);
           // Socket sck;


            clientSocket = _listener.EndAcceptTcpClient(asyn);
         IPAddress add= IPAddress.Parse(((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString());
         curIP = add.ToString();

          Form1 myform=new Form1();
          myform.items.add("client connectes with ip:"+curIP);
          **// lstIP.items.add("client connected with ip"+curIP); 
        // MessageBox.Show("cleint connected with ip:"+ curIP);**

            HandleClientRequest clientReq = new HandleClientRequest(clientSocket);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

        WaitForClientConnect();
    }

    public void btnStart_Click(object sender, EventArgs e)
    {
        StartServer();


    }
    private void InitialiseCPUCounter()
    {
        cpuCounter = new PerformanceCounter(
        "Processor",
        "% Processor Time",
        "_Total",
        true
        );
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        cpuLoad = Convert.ToInt32(cpuCounter.NextValue());
        this.txtCPUusage.Text =
 cpuLoad.ToString() +
 "%";
    }
  static  public string GetLocalIP()
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        return "127.0.0.1";
    }
}
    }

我知道了。 您在static方法中。 没有对象的引用,您将无法访问静态成员内的实例字段。

我的意思是你需要类似的东西

myForm.lstIP.items.add("client connected with ip"+curIP); 

但是,我建议您避免使用静态方法,并使其成为所有方法实例,然后一切都会好起来的。

另请注意, OnClientConnect将在辅助线程中调用,因此您无法在该位置更新UI。 请参阅如何从C#中的另一个线程更新GUI? 有关更多信息。

注意:请发布您遇到的错误,并提及它是编译时错误还是运行时异常。 我无法访问XXX它无法正常工作对我们理解问题没有帮助。 堆栈溢出问题清单


您的完整代码如下所示:

public partial class Form1 : Form
{
    public int cpuLoad;
    private PerformanceCounter cpuCounter;
    static public string curIP;
    public static string get_localip = GetLocalIP();

    public Form1()
    {
        InitializeComponent();
        InitialiseCPUCounter();
        timer1.Start();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        lblServerIP.Text += " " + get_localip;
    }
    private TcpListener _listener;

    public void StartServer()
    {
        System.Net.IPAddress localIPAddress = System.Net.IPAddress.Parse(get_localip);
        IPEndPoint ipLocal = new IPEndPoint(localIPAddress, 8888);
        _listener = new TcpListener(ipLocal);
        _listener.Start();
        WaitForClientConnect();

    }
    private void WaitForClientConnect()
    {
        object obj = new object();
        _listener.BeginAcceptTcpClient(new System.AsyncCallback(OnClientConnect), obj);
    }
    public void OnClientConnect(IAsyncResult asyn)
    {
        try
        {
            TcpClient clientSocket = default(TcpClient);
            // Socket sck;

            clientSocket = _listener.EndAcceptTcpClient(asyn);
            IPAddress add = IPAddress.Parse(((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString());
            curIP = add.ToString();

            //Use this.Invoke or this.BeginInvoke
            this.Invoke(new Action(() =>
            {
                lstIP.items.add("client connected with ip" + curIP);
                MessageBox.Show("cleint connected with ip:" + curIP);
            }));

            HandleClientRequest clientReq = new HandleClientRequest(clientSocket);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

        WaitForClientConnect();
    }

    public void btnStart_Click(object sender, EventArgs e)
    {
        StartServer();
    }
    private void InitialiseCPUCounter()
    {
        cpuCounter = new PerformanceCounter(
        "Processor",
        "% Processor Time",
        "_Total",
        true
        );
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        cpuLoad = Convert.ToInt32(cpuCounter.NextValue());
        this.txtCPUusage.Text = cpuLoad.ToString() + "%";
    }
    static public string GetLocalIP()
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        return "127.0.0.1";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM