Search code examples
c#winformsvisual-studio-2008consoleinteraction

WindowsForms difference to simple Console App


I currently started to "port" my console projects to WinForms, but it seems I am badly failing doing that.

I am simply used to a console structure:

I got my classes interacting with each other depending on the input coming from the console. A simple flow:

Input -> ProcessInput -> Execute -> Output -> wait for input

Now I got this big Form1.cs (etc.) and the "Application.Run(Form1);" But I really got no clue how my classes can interact with the form and create a flow like I described above.

I mean, I just have these "...._Click(object sender....)" for each "item" inside the form. Now I do not know where to place / start my flow / loop, and how my classes can interact with the form.


Solution

  • Pretty straightforward, actually (though I can sympathize with your confusion)...

    1. Input
    Have a TextBox and a Button. When the user clicks on the button, treat whatever's in your TextBox as your input.

    2. Process Input
    In a console app, the user is unable to do anything while you're processing input. The analogue to this in a Windows Forms app is to disable the mechanism by which the user can supply input. So, set your TextBox.Enabled = false and Button.Enabled = false.

    3. Execute
    Run whatever method you want to execute.

    4. Output
    Have some kind of message displayed on the form. This could be simply another TextBox, or a RichTextBox... whatever you want.

    5. Wait for Input
    Once your method from step 3 has executed, you've displayed the output in part 4, you can go ahead and re-activate your mechanism for accepting input: TextBox.Enabled = true and Button.Enabled = true.

    So basically your code should like something like this:

    void myButton_Click(object sender, EventArgs e) {
        try {
            myInputTextBox.Enabled = false;
            myButton.Enabled = false;
    
            var input = ParseInput(myInputTextBox.Text);
    
            var output = ExecuteMethodWithInput(input);
    
            myOutputTextBox.Text = FormatOutput(output);
    
        } finally {
            myInputTextBox.Enabled = true;
            myButton.Enabled = true;
        }
    }