I have been dealing with really strange thing. In debug mode or if Thread.Sleep is set above 1900ms everything is fine, but if I'm not in debug mode a function OnKeyPressed is called twice while the function is still running.I thought, that it's because EventHandler calls OnKeyPressed twice, but when I pressed the key programmatically nothing has changed. What's more I have observed that the Thread.Sleep is called just one time. How do I know the code is executed two times? I have 2 the same objects in my savedWords
collection.
Some details of the code I've written:
I have a Listbox<string> savedWords
where I keep text from clipboard. I am using an InputSimulator Framework to simulate keyboard events(only to send key combination). I have a simple InputClass where I obtain a method CopyText in order to simulate key combination of ctrl+c to save the text in clipboard. I'm not able to get into the clipboard if I'm not using STA Attribute, so it has to be there. In order to hook the keyboard(to listening if the key I want to is pressed) I'm using the second solution(with the HandledEventArgs) from here Global keyboard capture in C# application .
Here is my code:
private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
{
if (e.KeyboardData.VirtualCode==(int)Keys.F1)
{
string storedText="";
e.Handled = true;
System.Windows.Clipboard.Clear();
Thread.Sleep(50);
Thread t = new Thread(
() => { storedText = pasteMethod.CopyText(); }
);
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
System.Threading.Thread.Sleep(1900); // If I set the time below 1900 it executes twice
if (!String.IsNullOrWhiteSpace(storedText))
{
savedWords.Add(storedText); //Here I add the text from clipboard to my collection and it's the part of code which is called twice
}
}