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

时间:2014-08-08 09:36:47

标签: c#

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

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";
    }
}
    }

1 个答案:

答案 0 :(得分:0)

我明白了。您在static方法中。在没有对象引用的情况下,您无法访问静态成员中的实例字段。

我的意思是你需要像

这样的东西
myForm.lstIP.items.add("client connected with ip"+curIP); 

但是,我建议你避免静态并使所有方法实例,然后一切都会好的。

另请注意,OnClientConnect将在工作线程中调用,因此您无法在那里更新UI。有关详细信息,请参阅How to update the GUI from another thread in C#?

注意:请发布您获得的错误,并提及它是编译时错误还是运行时异常。 我无法访问XXX 它无效对我们理解问题没有帮助。 Stack Overflow question checklist

<小时/>

您的完整代码如下:

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";
    }
}