The Woo
The Woo

Reputation: 18645

Boolean Statement True For Length of Time

I have the following code:

private Boolean _penny = false;

public void InputTextbox_KeyDown(object sender, KeyEventArgs e)
{
   if (!_penny)
   {
      if (e.KeyCode == Keys.Enter & InputTextbox.Text.Contains("penny"))
      {
         _penny = true;
         OutputTextbox.Text = "yes sir";
         InputTextbox.Text = "";
      }
   }
}

This clears the InputTextbox so that it is ready for further input, and the commands that follow only run if the Boolean for _penny = true (ie: that the program has been ordered to listen for further commands).

At the moment, each text command ends with "_penny == false" so that the program essentially stops listening for anything.

My question is, can this Boolean value stay "true" for a length of time? ie: User says "penny", and they can ask multiple input questions for a number of minutes without having to say "penny" again.

Upvotes: 0

Views: 371

Answers (2)

The Woo
The Woo

Reputation: 18645

I used Nicholas Carey's solution, but slightly modified; for anyone who wants it here it is:

private DateTime _expiryTime;

public void InputTextbox_KeyDown(object sender, KeyEventArgs e)
   {
      if (e.KeyCode == Keys.Enter && InputTextbox.Text.Contains("penny"))
         {
            _expiryTime = DateTime.Now.AddMinutes(1);
            OutputTextbox.Text = "yes sir";
         }
else if (e.KeyCode == Keys.Enter && InputTextbox.Text.Contains("what time is it") && DateTime.Now < _expiryTime)
   {
code runs here...
   }

This sets the _expiryTime to when the word "penny" is entered into the Textbox. The user can then run any of the following commands they like for 1 minute.

Upvotes: 0

Nicholas Carey
Nicholas Carey

Reputation: 74197

While you could use a timer, that seems like overkill to me. All you need to do is track an expiry date/time:

private bool CurrentlyValidated
{
  get
  {
    return DateTime.Now < _expiryTime && _validated ;
  }
  set
  {
    _validated  = value ;
    _expiryTime = DateTime.Now.AddMinutes(5) ;
  }
}
private bool     _validated  ;
private DateTime _expiryTime ;

Upvotes: 3

Related Questions