开发者

Accessing a function in another form -- C#

I have this battleship program where i am trying to access a function in another form. This function is used to change the buttons on the game board to either enabled or disabled, depending on who's turn it is. Changing the buttons to enabled and disabled is not my problem. My problem is accessing the function to do it in the other form. I 开发者_开发技巧would post code, but it is lengthy and spread between three forms.

Appreciate any help!

Thanks in advance!

Luke


Why not pull the functionality out into its own public class (like ButtonConfigurator or something like that). Then any form can hold a ButtonConfigurator object and use it.


It depends on your code architecture:

  1. Kind of rough one: If you just have several forms Form _form1, Form2 _form2, you can create kind of relationship between them, by, just an example pseudocode:

    public class Form1:Form 
    {
        Form2 _form2Object = null;
    
        public Form1(Form2 frm2) 
        {
            _form2Object = frm2;
        }
    
        //and after when needed just use that _form2Object to call a mehod on it.
    }
    
  2. More nice one: is declare shared between all your forms event Dispatcher. So when Form1 wants to notify somethign to Form2 it calls Dispatchers relative method, which takes care to call right method on Form2

There could be a lot of other solutions more or less nicer, but it strongly depends on your app architecture. Here I just put down a couple of choices you could have.

Hope this helps. Regards.


you need pass the instance of the form with Button to the form you call the function, make the function public.


Lets suppose you have a Form form1 which has method method1, that you want to access in Form form2. You could declare that method as public static. This way you could access that method like form1.method1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜