Insert Text with a shortcut key

719 views Asked by At

I am inserting a text like 'xx--xx--xx\username' all the time. So I need something to insert a text after pressing Alt/Ctrl + another key.

After reading a bit about this problem I found some useful information:

How to detect the currently pressed key?

I have the problem to think how I can do this. Any other person should define his own 'xx--xx--xx\username' like he need it. So saving this into a file is the next step.

Are there any threads on Stack Overflow about this problem? I couldn't find any results, maybe I was searching wrong.

1

There are 1 answers

2
Bernd Linde On BEST ANSWER

To capture the KeyDown event with which you detect if a user has pressed the keybord shortcut, handle the event KeyDown with this code (where txtInput is the TextBox)

this.txtInput.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtInput_KeyDown);

Now create that mentioned method (txtInput_KeyDown) and add the following code to handle specific shortcuts
(P.S. to handle the event and create the method in VisualStudio, just double click on the KeyDown even in the properties)

// Shortcut Alt+I
if (e.Alt && (e.KeyCode == Keys.I))
{
  txtInput.Text = @"somedomain\" + txtInput.Text; // Adds the text to the front of the current text
  txtInput.SelectionStart = txtInput.Text.Length; // Sets the cursor to the end of the text
}
// Shortcut Ctrl+K
else if (e.Control && (e.KeyCode == Keys.K))
{
  txtInput.Text += @"networkpath\"; // Adds the text to the back of the current text
  txtInput.SelectionStart = txtInput.Text.Length; // Sets the cursor to the end of the text
}

As described in the comments in the code, this code will handle two different shortcut combinations differently, modify according to your needs.

Additional reading up can be done here regarding the KeyDown event.

The next step that you mentioned was to save the information and load it when the application starts up again, read the SO posts here and here regarding storing and retrieving user settings.

The MSDN entries regarding user settings:
Using Application Settings and User Settings
How To: Write User Settings at Run Time with C#
Using Settings in C#