Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

c# - Capture Key Sequence via ProcessCmdKey

I override ProcessCmdKey in my application and can get any single keypress with modifiers (eg. Alt+Ctrl+X). What I want to do is mimic the short cut handling of say ReSharper where the user holds down the control key and then R, M to open the refactor dialog

I have found plenty of references to capture key plus modifier combinations but not much for the sequence. There is this Capture multiple key downs in C# but it uses the KeyDown Event.

There are also key mining examples such as this http://www.codeproject.com/KB/system/simple_key_log.aspx that capture everything and use native calls.

Am I able to extend my ProcessCmdKey to handle the key sequences or do I need to look elsewhere? Since I have a large number of shortcuts captured in ProcessCmdKey I would rather not have to start again if possible

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order to achieve the functionality you want you simply need to keep track of the sequence of KeyPress events.

You can create a class to keep track of the last key combination that was pressed in ProcessCmdKey. If that particular combination does not match a mapped command but it is the first element of a sequence you can store it in your class. Then the next time ProcessCmdKey is activated check your new KeyPressTracker class to determine if a sequence has been started. If it has then check if the newly pressed key combination is the second element of one you specify. Please see the pseudocode example below:

Step 1: ProcessCmdKey is activated. The key combination is Ctrl+R, this does not match a command that you want to process but it is the first element of a sequence that you want to use (Ctrl+R+M).

Step 2: Store this key-press in a new class you created to keep track of the last key-press.

KeyPressTracker.Store(KeyCode, Modifiers);

Step 3: ProcessCmdKey is activated a second time. This time, the key combination is Ctrl+M which is not a key-press we're looking for but is the second element of a sequence. We check the last stored keypress using the new KeyPressTracker class. This will allow you to match a "sequence" such as Ctrl+R and Ctrl+M.

var lastKeyPress = KeyPressTracker.GetLastKeyPress();

if (lastKeyPress == "Ctrl+R" && currentKeyPress == "Ctrl+M")
{   
    // Show Refactor dialog
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...