Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6882367
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T05:14:40+00:00 2026-05-27T05:14:40+00:00

I’ve got a working test state machine in a console app – 3 states

  • 0

I’ve got a working test state machine in a console app – 3 states and 5 events.

Problem: How to run in Windows Forms ie do I have a main loop which is running all the time looking at state..and if so where…if am using events ie btnPress.

The goal is that the app can be in a number of different states/screens and it needs to be solid, so using a state machine to enforce where we are, and that there are no edge cases unhandled.

Working console app code:

namespace StateMachineTest {
class Program {
    static void Main(string[] args) {
        var fsm = new FiniteStateMachine();
        while (true) {
            if (fsm.State == FiniteStateMachine.States.EnterVoucherCode) {
                Console.WriteLine("State: " + fsm.State);
                Console.WriteLine("Enter Voucher Code:");
                string voucherCode = Console.ReadLine();
                Console.WriteLine("voucher is " + voucherCode);
                Console.WriteLine();
                fsm.ProcessEvent(FiniteStateMachine.Events.PressNext);
            }

            if (fsm.State == FiniteStateMachine.States.EnterTotalSale) {
                Console.WriteLine("State: " + fsm.State);
                Console.WriteLine("Enter Total Sale or x to simulate back");
                string voucherSaleAmount = Console.ReadLine();
                if (voucherSaleAmount == "x")
                    fsm.ProcessEvent(FiniteStateMachine.Events.PressBackToVoucherCode);
                else {
                    Console.WriteLine("total sale is " + voucherSaleAmount);
                    Console.WriteLine();
                    fsm.ProcessEvent(FiniteStateMachine.Events.PressRedeem);
                }
            }

            if (fsm.State == FiniteStateMachine.States.ProcessVoucher) {
                Console.WriteLine("State: " + fsm.State);
                Console.WriteLine("Press 1 to fake a successful redeem:");
                Console.WriteLine("Press 2 to fake a fail redeem:");
                Console.WriteLine("Press 3 to do something stupid - press the Next Button which isn't allowed from this screen");
                Console.WriteLine();
                string result = Console.ReadLine();

                //EnterVoucherCode state
                if (result == "1")
                    fsm.ProcessEvent(FiniteStateMachine.Events.ProcessSuccess);
                if (result == "2")
                    fsm.ProcessEvent(FiniteStateMachine.Events.ProcessFail);
                if (result == "3")
                    fsm.ProcessEvent(FiniteStateMachine.Events.PressNext);
            }

            //how to handle async calls?
            //how to handle many many states.. matrix could get unwieldy
        }
    }
}

class FiniteStateMachine {
    //first state is the default for the system
    public enum States { EnterVoucherCode, EnterTotalSale, ProcessVoucher };
    public enum Events { PressNext, PressRedeem, ProcessSuccess, ProcessFail, PressBackToVoucherCode };
    public delegate void ActionThing();

    public States State { get; set; }

    private ActionThing[,] fsm;

    public FiniteStateMachine() {
        //array of action delegates
        fsm = new ActionThing[3, 5] { 
        //PressNext,     PressRedeem,            ProcessSuccess,      ProcessFail,      PressBackToVoucherCode
        {PressNext,      null,                   null,                null,             null},                          //EnterVoucherCode.... can pressnext
        {null,           PressRedeem,            null,                null,             PressBackToVoucherCode},        //EnterTotalSale... can pressRedeem or pressBackToVoucherCode
        {null,           null,                   ProcessSuccess,      ProcessFail,      null} };                        //moving from ProcessVoucher... can be a processSuccess or ProcessFail.. can't go back to redeem
    }
    public void ProcessEvent(Events theEvent) {
        try {
            var row = (int)State;
            var column = (int)theEvent;
            //call appropriate method via matrix.  So only way to change state is via matrix which defines what can and can't happen.
            fsm[row, column].Invoke();
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message); //possibly catch here to go to an error state? or if do nothing like here, then it will continue on in same state
        }
    }

    private void PressNext() { State = States.EnterTotalSale; }
    private void PressRedeem() { State = States.ProcessVoucher; }
    private void ProcessSuccess() { State = States.EnterVoucherCode; }
    private void ProcessFail() { State = States.EnterVoucherCode; }
    private void PressBackToVoucherCode() { State = States.EnterVoucherCode; }
}

}

Not working WinForms code:

    //goal is to get a fsm demo working with 3 states and 5 events.
//need number buttons, redeem and back to work.
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void MainForm_Load(object sender, EventArgs e) {
        SystemSettings.ScreenOrientation = ScreenOrientation.Angle90;

        var fsm = new FiniteStateMachine();
        while (true)
        {
            if (fsm.State == FiniteStateMachine.States.EnterVoucherCode)
            {
                //Console.WriteLine("State: " + fsm.State);

                //if next/redeem button is pressed
                //fsm.ProcessEvent(FiniteStateMachine.Events.PressNext);
            }

            if (fsm.State == FiniteStateMachine.States.EnterTotalSale)
            {
                Console.WriteLine("State: " + fsm.State);
                Console.WriteLine("Enter Total Sale or x to simulate back");
                string voucherSaleAmount = Console.ReadLine();
                if (voucherSaleAmount == "x")
                    fsm.ProcessEvent(FiniteStateMachine.Events.PressBackToVoucherCode);
                else
                {
                    Console.WriteLine("total sale is " + voucherSaleAmount);
                    Console.WriteLine();
                    fsm.ProcessEvent(FiniteStateMachine.Events.PressRedeem);
                }
            }

            if (fsm.State == FiniteStateMachine.States.ProcessVoucher)
            {
                Console.WriteLine("State: " + fsm.State);
                Console.WriteLine("Press 1 to fake a successful redeem:");
                Console.WriteLine("Press 2 to fake a fail redeem:");
                Console.WriteLine("Press 3 to do something stupid - press the Next Button which isn't allowed from this screen");
                Console.WriteLine();
                string result = Console.ReadLine();

                //EnterVoucherCode state
                if (result == "1")
                    fsm.ProcessEvent(FiniteStateMachine.Events.ProcessSuccess);
                if (result == "2")
                    fsm.ProcessEvent(FiniteStateMachine.Events.ProcessFail);
                if (result == "3")
                    fsm.ProcessEvent(FiniteStateMachine.Events.PressNext);
            }
        }
    }

    private void btn_0_MouseUp(object sender, MouseEventArgs e)
    {
            txtCode.Text += '0';
    }

    private void btn_1_MouseUp(object sender, MouseEventArgs e)
    {
            txtCode.Text += '1';
    }

    private void btn_2_MouseUp(object sender, MouseEventArgs e)
    {
            txtCode.Text += '2';
    }

    private void btn_del_MouseUp(object sender, MouseEventArgs e)
    {
            txtCode.Text = txtCode.Text.Substring(0, txtCode.Text.Length - 1);
    }

    private void btn_redeem_MouseUp(object sender, MouseEventArgs e)
    {
            txtCode.Visible = false;
            txtStatus.Visible = true;
            txtStatus.Text = "PROCESSING PLEASE WAIT";
    }

enter image description here

Code from:
Simple state machine example in C#?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T05:14:40+00:00Added an answer on May 27, 2026 at 5:14 am

    There is no need to have a polling event loop that’s constantly checking the state, that’s what a WinForm does automatically. You should have your UI elements wire up event handlers, and those event handlers should be responsible for checking/toggling state.

    This is a very dirty implementation. If you apply the State Pattern (Chapter 9 of Head First Design Patterns has a really clean example), you should be able to use your Form as the Client that holds another object corresponding to the Context that is called by the event handlers of your UI elements.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I've got a string that has curly quotes in it. I'd like to replace
I am currently running into a problem where an element is coming back from
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
i got an object with contents of html markup in it, for example: string
I am writing an app with both english and french support. The app requests
I am using Paperclip to handle profile photo uploads in my app. They upload
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.