Calling a function in the Form Class from another Class, C# .NET

前端 未结 5 577
悲&欢浪女
悲&欢浪女 2020-12-28 21:28

Can someone please let me know by some code how I can call a function located in the Form class from another class?

Some code will be of great help!

thanks

5条回答
  •  长发绾君心
    2020-12-28 21:59

    It's quite easy. Either pass a reference to an existing form in the call, or create a new instance of your form and then call your method just like any other:

    public class MyForm : Form
    {
        public void DoSomething()
        {
            // Implementation
        }
    }
    
    public class OtherClass
    {
        public void DoSomethingElse(MyForm form)
        {
            form.DoSomething();
        }
    }
    

    Or make it a static method so you don't have to create an instance (but it won't be able to modify open form windows).

    UPDATE

    It looks like the ImageProcessing class never gets a reference to the form. I would change your code slightly:

    class ImageProcessing
    {
        private frmMain _form = null;    
    
        public ImageProcessing(frmMain form)
        {
            _form = form;
        }
    
        private UpdateStatusLabel(string text)
        {
            _form.StatusUpdate(text);
        }
    }
    

    And then one small tweek in the Form constructor:

    ImageProcessing IP = new ImageProcessing(this);
    

提交回复
热议问题