如何从Windows窗体

时间:2016-04-13 01:04:24

标签: c# visual-studio-2010 image-processing static-methods windows-forms-designer

我希望我的问题与回答有关,因为我是新手。

例如,我有两个名为“Class1.cs”和“Form1.cs”的编码。基本上,Class1.cs是发生图像过滤过程的程序,同时在“Form1.cs”中是允许它从文件加载图像的程序。在我点击按钮处理它之后,我可以立即从“Form1.cs”访问“Class1.cs”吗?

  

的Class1.cs

namespace MyProgram
{
 class Class1
 {
  public static class Class1Program
  {
     //my program for image filtering is starting at here
  }
 }
}
  

Form1.cs的

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

  private void LoadImageButton_Click(object sender, EventArgs e)
  {
   //My program here is to open up a file image right after I click on this button
  }

  private void ResultButton_Click(object sender, EventArgs e)
  {
    // Here is the part where I don't know how to access the program from "Class1.cs".
    // I'm expecting the image that I've load before will be able to filter right after I clicked on this button
  }
 }
}

我想知道是否需要在“Program.cs”上添加或编辑某些程序。

我希望我的问题能得到解答。非常感谢你的时间。

2 个答案:

答案 0 :(得分:0)

您可以执行以下两项操作之一:

1.您可以使用静态变量访问Class1中的数据:

namespace MyProgram
{
    class Class1
    {
        public static int Class1Variable;
    }
}

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

        private void LoadImageButton_Click(object sender, EventArgs e)
        {
            //Load image logic
        }

        private void ResultButton_Click(object sender, EventArgs e)
        {
            Class1.Class1Variable = 1;
        }
    }
}

2.您可以在Form1中创建Class1的实例:

namespace MyProgram
{
    class Class1
    {
        public int Class1Variable;

        public Class1()
        {
        }
    }
}

namespace MyProgram
{
    public partial class Form1 : Form
    {
        public Class1 c1;

        public Form1()
        {
            InitializeComponent();
            c1 = new Class1();
        }

        private void LoadImageButton_Click(object sender, EventArgs e)
        {
            //Load image logic
        }

        private void ResultButton_Click(object sender, EventArgs e)
        {
            c1.Class1Variable = 1;
        }
    }
}

答案 1 :(得分:0)

让我为静态类添加一个属性和方法,使其易于理解。让Class1Program如下所示:

public static class Class1Program
{  
    public static int MyProperty{get; set;} // is a static Property
    public static void DoSomething() // is a static method for performing the action
    {
        //my program for image filtering is starting at here
    }

}

现在您可以像{i>}一样访问Form1内的方法和属性:

 private void ResultButton_Click(object sender, EventArgs e)
 {
    Class1.Class1Program.MyProperty = 20; // assign 20 to MyProperty
    int myint = Class1.Class1Program.MyProperty; // access value from MyProperty
    Class1.Class1Program.DoSomething();// calling the method to perform the action
 }