如何在第二窗口窗体上显示数据?

时间:2013-11-10 14:20:48

标签: c# winforms

在我的主窗口中,我创建了一个执行while()循环的线程。主要任务包括两部分:从套接字接收数据并在GUI上显示。

现在我需要同时在另一个窗口上显示数据。所以我先创建它,如下所示。

ShowForm showForm = new ShowForm();

public MainWindow()
{
    InitializeComponent();

    mainThread();

    showForm.Show();
}

并将数据发送到showForm,如下所示:(在主窗口中生成coordinateValue

showForm.setter(coordinateValue);

在ShowForm.Designer.cs的代码中:

int xValue;

public void setter(int val)
{
    xValue = val;
}

现在我不知道如何反复在showForm上显示xValue(需要及时更新),例如textBox或将xValue转换为坐标并在pictureBox上显示它。同时,主窗口的while()循环应继续接收数据并在其GUI上显示。

有人可以帮忙吗?谢谢!

3 个答案:

答案 0 :(得分:0)

您可以在MainWindow中创建活动。并在ShowForm中订阅该事件。

比数据更改时,MainWindow应该引发该事件。请记住,如果您在另一个线程中获取数据,则不能将其传递给在主线程上运行的GUI。在这种情况下,您将需要使用Dispatcher。

答案 1 :(得分:0)

您可能想要使用Timer类。它可以偶数间隔执行方法(Tick事件)。

答案 2 :(得分:0)

我写了一个示例,解释了如何使用事件将数据从一个表单传输到另一个表单。如果它在另一个线程中运行,您应该在控件中使用Invoke方法来防止错误。

public partial class AdditionalForm : Form
{
    private Label l_dataToShow;

    public Label DataToShow { get { return l_dataToShow; } }

    public AdditionalForm()
    {
        InitializeComponent();

        SuspendLayout();
        l_dataToShow = new Label();
        l_dataToShow.AutoSize = true;
        l_dataToShow.Location = new Point(12, 9);
        l_dataToShow.Size = new Size(40, 13);
        l_dataToShow.TabIndex = 0;
        l_dataToShow.Text = "Data will be shown here";
        Controls.Add(l_dataToShow);
        ResumeLayout();
    }
}

public partial class MainForm : Form
{
    private AdditionalForm af;
    public MainForm()
    {
        InitializeComponent();

        SuspendLayout();
        txtbx_data = new TextBox();
        txtbx_data.Location = new System.Drawing.Point(12, 12);
        txtbx_data.Name = "txtbx_data";
        txtbx_data.Size = new System.Drawing.Size(100, 20);
        txtbx_data.TabIndex = 0;
        Controls.Add(txtbx_data);
        ResumeLayout();

        txtbx_data.TextChanged += new EventHandler(txtbx_data_TextChanged);
        af = new AdditionalForm();
        af.Show();
    }
    /// <summary>
    /// The data that contains textbox will be transfered to another form to a label when you will change text in a textbox. You must make here your own event that will transfer data.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void txtbx_data_TextChanged(object sender, EventArgs e)
    {
        af.DataToShow.Text = txtbx_data.Text;
    }
}
相关问题