2

I'm writing a simple encryptor program. When I type in the first textbox the encrypted text appears on the second textbox on the fly using the textchanged event. I also have a button to load key files. My problem is if I type first in to the textbox and then load a keyfile afterwards the encrypting handler is not called, because it's hooked to the textchanged event, and I have to write something to the first textbox to invoke it.

To solve this I hooked 2 events to the load button's click event, one is loading the key file, and the other is the same that is hooked to the textchanged event. (I would really like to avoid code duplication.)

This is working correctly, but how can I be sure, that everytime the key file loading happens and finishes before the encrypting function is called? Is there a better way to do this?

user3548320
  • 21
  • 1
  • 5

2 Answers2

3

You should consider creating separate methods:

private List<string> keyCodes;

private void LoadKeyCodesButton_Click(object sender, RoutedEventArgs e)
{
    LoadKeyCodes();
    UpdateOutput();
}

private void InputTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    UpdateOutput();
}

private void LoadKeyCodes()
{
    // load key codes here
    keyCodes = new List<string>();
    // etc.
}

private void UpdateOutput()
{
    OutputTextBox.Text = EncryptText(InputTextBox.Text);
}

private string EncryptText(string input)
{
    // use keyCodes to encrypt
    return input;
}

The encryption could even be placed inside a separate class, but this would help you get started.

Silvermind
  • 5,791
  • 2
  • 24
  • 44
1

It looks like you are trying to chain your events. It could be done by calling your TextChangedEvent from the KeyFilesLoadedEvent (or whatever they are called)

public event TextChangedEventHandler TextChangedEvent;
public event KeyFilesLoadedEventHandler KeyFilesLoadedEvent;

KeyFilesLoadedEvent += (sender, e) =>
{
    /* the rest of your code for the KeyLoadedEvent  */
    TextChangedEventHandler handler = TextChangedEvent;
    if(handler != null)
    {
        handler(this, e);
    }
};
frich
  • 145
  • 5