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

前端 未结 5 586
悲&欢浪女
悲&欢浪女 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 22:11

    A quick and dirty way is to create a reference of the MainForm in your Program.cs file as listed above.

    Alternatively you can create a static class to handle calls back to your main form:

        public delegate void AddStatusMessageDelegate (string strMessage);
    
        public static class UpdateStatusBarMessage
            {
    
            public static Form mainwin;
    
            public static event AddStatusMessageDelegate OnNewStatusMessage;
    
            public static void ShowStatusMessage (string strMessage)
                {
                ThreadSafeStatusMessage (strMessage);
                }
    
            private static void ThreadSafeStatusMessage (string strMessage)
                {
                if (mainwin != null && mainwin.InvokeRequired)  // we are in a different thread to the main window
                    mainwin.Invoke (new AddStatusMessageDelegate (ThreadSafeStatusMessage), new object [] { strMessage });  // call self from main thread
                else
                    OnNewStatusMessage (strMessage);
                }
    
            }
    

    Put the above into your MainForm.cs file inside the namespace but separate from your MainForm Class.
    Next put this event call into your MainForm.cs main class.

         void UpdateStatusBarMessage_OnNewStatusMessage (string strMessage)
         {
              m_txtMessage.Caption = strMessage;
         }
    

    Then when you initialise the MainForm.cs add this event handle to your form.

         UpdateStatusBarMessage.OnNewStatusMessage += UpdateStatusBarMessage_OnNewStatusMessage;
    

    In any UserControl or form associated with the form (MDI) that you want to call, just us the following...

         UpdateStatusBarMessage.ShowStatusMessage ("Hello World!");
    

    Because it is static it can be called from anywhere in your program.

提交回复
热议问题