views:

79

answers:

2

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.

+3  A: 

Basically, you can have your form provide a set of controls for inputting data (ie: one or more TextBox controls). If you have a button that the user clicks, and you want to process, just double click on teh button. This will give you an event handler like:

private void button1_Click(object sender, EventArgs e)
{
     // Process Input from TextBox controls, etc.
     // Execute method
     // Set output (To other controls, most likely)
}

That's it - the "loop" goes away, since the standard Windows message pump takes its place.

Reed Copsey
so I have to look at each event handler like it is a "little flow"?
daemonfire300
@daemonfire300: Basically, it's an "entry point" to your processing. You're saying "when the user clicks this button, I want to run this code..." so it provides a way for you to "process" and start your flow control.
Reed Copsey
+5  A: 

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;
    }
}
Dan Tao