C# 类中操作主窗体控件

时间:2022-07-23
本文章向大家介绍C# 类中操作主窗体控件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

主窗体程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp20
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Class1 cs = new Class1();
            cs.test();
        }
    }
}

class1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp20
{
    class Class1
    {
        public void test()
        {

            Form1 f1 = new Form1();
            f1.richTextBox1.Text = "123";
        }
    }
}

运行结果啥也没,。。。。。。。。。

解决办法:

将窗体作为参数传入类,然后可以根据属性来对其进行相应的操作

实例修改如下:

主窗体程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp20
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Class1 cs = new Class1();
            cs.test(this);
        }
    }
}

class1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp20
{
    class Class1
    {
        public void test(Form1 obj)
        {

          
            obj.richTextBox1.Text = "123";
        }
    }
}

是不是很简单!!!

运行结果:别忘了将主控件的modifiers属性改为public

这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!这种方法简单实用!