Capture combination key event in a Windows Forms application
Handle the KeyDown
event and have something like:
if (e.Modifiers == Keys.Shift && e.KeyCode == Keys.Up)
{
MessageBox.Show("My message");
}
The event handler has to be on the Main Form and you need to set the KeyPreview
property to true
. This can be done in design mode from the properties dialog.
get combination from a list of key-values
Quick & dirty but you may polish this method. The result list contains expected result:
Usage:
var dict = new Dictionary<String, List<String>>() {
{"1",new List<String>(){"a", "b"}},
{"2",new List<String>(){"c", "d", "e"}},
{"3",new List<String>(){"f", "g"}},
};
var collections = dict.Select(kvp => kvp.Value).ToArray();
var result = new List<string>();
GetNextProduct(collections, 0, String.Empty, result);
Method that produces the result:
private static void GetNextProduct(IEnumerable<string>[] collections, int collectionIndex, string currentProduct, IList<string> results)
{
var currentList = collections[collectionIndex];
bool isLast = collections.Length == collectionIndex + 1;
foreach (var s in currentList)
{
if (isLast) results.Add(currentProduct + s);
else GetNextProduct(collections, collectionIndex + 1, currentProduct + s, results);
}
}
Detect key combination being pressed in C# console app
If you capture the ConsoleKeyInfo
, you will get additional information, including the Modifiers
keys. You can query this to see if the Control key was pressed:
ConsoleKey key;
do
{
while (!Console.KeyAvailable)
{
// Do something, but don't read key here
}
// Key is available - read it
var keyInfo = Console.ReadKey(true);
key = keyInfo.Key;
if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
{
Console.Write("Ctrl + ");
}
if (key == ConsoleKey.NumPad1)
{
Console.WriteLine(ConsoleKey.NumPad1.ToString());
}
else if (key == ConsoleKey.NumPad2)
{
Console.WriteLine(ConsoleKey.NumPad2.ToString());
}
} while (key != ConsoleKey.Escape);
Key combination shortcut
After a long search and experiment, a solution has finally been found
https://stackoverflow.com/a/12676910/8152725
How to calculate keys combination in c#
Console.Write((int) (Keys.Alt | Keys.F))
Or more basic:
1000000000000000000 OR 1000110 = 1000000000001000110
Display all keys combination
I believe you are looking for GetKeyboardState function. I will give you status of all virtual keys in one call. The GetAsyncKeyState function is better used to check if the user pressed a key or not.
As an exercise, I wrote the following to demonstrate the GetAsyncKeyState API call:
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace s26244308
{
class Program
{
static void Main(string[] args)
{
bool keepGoing = true;
while (keepGoing)
{
int wasItPressed = SysWin32.GetAsyncKeyState(SysWin32.VK_ESCAPE);
if (wasItPressed != 0)
{
keepGoing = false; // stop
continue;
}
// for this sample: just loop a few letters
for (int x = 0x41; x <= 0x4A; x++)
{
int letterPressed = SysWin32.GetAsyncKeyState(x);
if (letterPressed != 0)
{
// now check for a few other keys
int shiftAction = SysWin32.GetAsyncKeyState(SysWin32.VK_SHIFT);
int ctrlAction = SysWin32.GetAsyncKeyState(SysWin32.VK_CONTROL);
int altAction = SysWin32.GetAsyncKeyState(SysWin32.VK_MENU);
// format my output
string letter = string.Format("Letter: {0} ({1})", Convert.ToChar(x), KeyAction(letterPressed));
string shift = string.Format("Shift: {0}", KeyAction(shiftAction));
string ctrl = string.Format("Control: {0}", KeyAction(ctrlAction));
string alt = string.Format("Alt: {0}", KeyAction(altAction));
Console.WriteLine("{0,-20}{1,-18}{2,-18}{3,-18}", letter, shift, ctrl, alt);
break;
}
}
Thread.Sleep(10);
}
Console.WriteLine("-- Press Any Key to Continue --");
Console.ReadLine();
}
private static string KeyAction(int pressed)
{
if (pressed == 0)
return "Up";
// check LSB
if (IsBitSet(pressed, 0))
return "Pressed";
// checked MSB
if (IsBitSet(pressed, 15))
return "Down";
return Convert.ToString(pressed, 2);
}
private static bool IsBitSet(int b, int pos)
{
return (b & (1 << pos)) != 0;
}
}
class SysWin32
{
public const int VK_ESCAPE = 0x1B;
public const int VK_SHIFT = 0x10;
public const int VK_CONTROL = 0x11;
public const int VK_MENU = 0x12;
[DllImport("user32.dll")]
public static extern int GetAsyncKeyState(Int32 i);
}
}
here is the console output:
Related Topics
Removing Dynamically Created Controls in C#
Play Multiple Sounds Using Soundplayer
Stop SQL Query Execution from .Net Code
Is Unityscript/JavaScript Discontinued
How to Create Roles in ASP.NET Core and Assign Them to Users
What's a Good Way to Overwrite Datetime.Now During Testing
Large Wcf Web Service Request Failing with (400) Http Bad Request
Best Way to Take Screenshots of Tests in Selenium 2
Iterating Over JSON Object in C#
Right Way to Dispose Image/Bitmap and Picturebox
Is There a Reasonable Approach to "Default" Type Parameters in C# Generics
Executing Query with Parameters
Regex Split String But Keep Separators
Encoding Space Character in Xml Name
Custom Authentication in ASP.NET-Core