主窗体程序:


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

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(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

C# 类中操作主窗体控件_推送_02


02





C# 类中操作主窗体控件_项目实战_03