I learned about Control.ModifierKeys
in this thread and this thread, and FileSystemWatcher
here and a FileSystemWatcher-specific workaround here. However, when I combine the two, I'm running into a strange, but explainable, bug. At least, I have a hypothesis.
My form uses a FileSystemWatcher
to detect changes to a file and run something whenever it triggers. However, the thing it runs is a bit distracting and time wasting, so I'm trying to get it to skip the run if the save is done by Ctrl+S, i.e. when the Control key is held down.
The code is something like this:
private void onFileChanged(object source, FileSystemEventArgs e)
{
// The try/finally blocks prevent double raising of the changed event
try
{
myFileWatcher.EnableRaisingEvents = false;
if ((ModifierKeys & Keys.Control) != 0)
MessageBox.Show("Control held down!");
else
{
MessageBox.Show("Running stuff!");
}
}
finally
{
myFileWatcher.EnableRaisingEvents = true;
}
}
So that's all fine, noting that the two MessageBox.Show
calls replace in-block code. Under normal use, it works. However, there is a very small time lag between the saving of the file and the triggering of onFileChanged
. If the Ctrl key is released before onFileChanged
triggers, i.e. if you tap Ctrl+S very quickly, very strange behavior results. For one, obviously, the Control key is not detected, but from here, even if you hold down Control after Ctrl+S until the popup shows, ModifierKeys
will still be 0 and it will think Ctrl is not being held down. And then, if you hold down Ctrl while clicking the OK in the popup, all of a sudden ModifierKeys
will keep firing the Control key even if you go File->Save in the file it's watching.
Is there a way to defeat this bug, or do I have to chalk it up as unfixable and tell my users to leave the Control key held down longer than they normally would in order to avoid this bug?