Ending the Program by pressing the Escape-Button

HomeForumsMonoBrick EV3 FirmwareEnding the Program by pressing the Escape-Button

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #3940

    Hi,

    My problem is that i want to close the program instantly when the “Escape” Button on the EV3 is pressed(even if its in a while-loop or something similar)… My current code looks like this:

    using System;  
    using MonoBrickFirmware;  
    using MonoBrickFirmware.Movement;  
    using MonoBrickFirmware.Display;  
    using MonoBrickFirmware.Sensors;  
    using MonoBrickFirmware.UserInput;  
    using System.Threading; 
    
    namespace ColorSensorExample  
    {  
    	class R_Main  
    	{  
    		public static void Main (string[] args)
    		{  
    			R_Main main = new R_Main ();
    		}
    
    		public R_Main()
    		{
    			  
    			var sensor = new EV3ColorSensor (SensorPort.In2);  
    			ButtonEvents buts = new ButtonEvents ();  
    			buts.EscapePressed += new Action(onEscape);
    			while (true) 
    			{
    				//Main-Code
    			}
    		}
    
    		private void onEscape()
    		{
    			EventWaitHandle stopped = new ManualResetEvent (false);
    			stopped.Set ();  
    		}			  
    	} 
    }

    But it does not work. While using the “KeyTest”-Example from the Monobrick Homepage, there is no problem.

    #3942
    Author Image
    Jacek S
    Participant

    Hi,
    Your program never ends because you must start main loop in separate thread and place wait event at the end of main thread.

    
    using System.Threading;
    using System.Threading.Tasks;
    using MonoBrickFirmware.UserInput;
    
    namespace EV3Program
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                ManualResetEvent terminateProgram = new ManualResetEvent(false);
                ButtonEvents buts = new ButtonEvents();
    
                buts.EscapePressed += () =>
                {
                    terminateProgram.Set();
                };
    
                var myLogic = new MyLogic();
    
                Task.Factory.StartNew(() => myLogic.Run());
    
                terminateProgram.WaitOne();
            }
        }
    }
    

    Jacek

    #3943

    Thanks so much it works perfectly now!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

Posted in

Make a donation