Swap alt keys functionality - windows

I need to swap Alt keys functionality in Windows 7. A big company needs that for old people that were writing on typewriters, which had diacritic characters key on the left side, but Win7 which they are working on now has right Alt for this purpose.
Two days of research brought me to a driver solution. I need source code for original Windows 7 drivers (two .sys files seem to be the keyboard drivers), and possibily to modify them in Windows DDK. Or I need to make an additional driver that would work with the default ones. As I can see, the solution would be in C or C++. But what way do I have to go to accomplish this? What steps should I take?
The limits are:
One system restart only for driver installation.
A simple way to swap Alt keys while working in Win7 (swap Alt keys by pressing them both).
No Win7 keyboard remapping which needs a restart.
Added later: I have everything I need, but not the code that will handle the swapping. For example, I've made a switch for right Shift and Enter, because there is only one scancode sent. But left Alt sends one and right Alt sends two scancodes:
VOID
KbFilter_ServiceCallback(
IN PDEVICE_OBJECT DeviceObject,
IN PKEYBOARD_INPUT_DATA InputDataStart,
IN PKEYBOARD_INPUT_DATA InputDataEnd,
IN OUT PULONG InputDataConsumed
)
/*++
Routine Description:
Called when there are keyboard packets to report to the Win32 subsystem.
You can do anything you like to the packets. For instance:
o Drop a packet altogether
o Mutate the contents of a packet
o Insert packets into the stream
Arguments:
DeviceObject - Context passed during the connect IOCTL
InputDataStart - First packet to be reported
InputDataEnd - One past the last packet to be reported. Total number of
packets is equal to InputDataEnd - InputDataStart
InputDataConsumed - Set to the total number of packets consumed by the RIT
(via the function pointer we replaced in the connect
IOCTL)
Return Value:
Status is returned.
--*/
{
PDEVICE_EXTENSION devExt;
WDFDEVICE hDevice;
hDevice = WdfWdmDeviceGetWdfDeviceHandle(DeviceObject);
devExt = FilterGetData(hDevice);
if (InputDataStart->MakeCode==0x1c)
InputDataStart->MakeCode=0x36;
else if (InputDataStart->MakeCode==0x36)
InputDataStart->MakeCode=0x1c;
else if (InputDataStart->MakeCode==0x9c)
InputDataStart->MakeCode=0xb6;
else if (InputDataStart->MakeCode==0xb6)
InputDataStart->MakeCode=0x9c;
(*(PSERVICE_CALLBACK_ROUTINE)(ULONG_PTR) devExt->UpperConnectData.ClassService)(
devExt->UpperConnectData.ClassDeviceObject,
InputDataStart,
InputDataEnd,
InputDataConsumed);
}
So I simply swap the scancodes of pressing and releasing both keys individually. Right Alt is sending two scancodes and I'm not sure if it does that by two calls of this function or makes two scancodes in the InputDataStart structure. I'll try to beep every Alt scancode but your help would be appreciated.

Solution:
if (InputDataStart->MakeCode==0x38 || InputDataStart->MakeCode==0xb8)
InputDataStart->Flags^=KEY_E0;
which swaps right-left Alt keys functionality.
Now I need to make the swapping configurable. For the best - by pressing both Alts.

Related

How to overhear a neighbor mote Tx/Rx in Contiki?

I want to know in RPL networks, after a node sends one packet to another node (for example RPL-Collect/udp-sender), how to know that intended node will forward this packet or not? I think overhearing neighbors transmission is needed, but is the another simple way to implemented this scenario in Contiki/Cooja?
To overhear packets in addition to normal operation you need to do several things:
Ensure that the radio is turned on and in the right channel. If you're using always-on CSMA or ContikiMAC you don't need to do anything special. Same for TSCH minimal schedule. Otherwise for TSCH you need to schedule a Rx cell with the right channel offset and in the right timeslot.
Somehow hack into the MAC layer to print or account packets not addressed to you - normally the MAC layer silently drops such packets.
Ensure hardware frame filtering is turned off (the radio is in promiscious mode).
Example:
radio_value_t radio_rx_mode;
/* Entering promiscuous mode so that the radio accepts all frames */
NETSTACK_RADIO.get_value(RADIO_PARAM_RX_MODE, &radio_rx_mode);
NETSTACK_RADIO.set_value(RADIO_PARAM_RX_MODE, radio_rx_mode & (~RADIO_RX_MODE_ADDRESS_FILTER));
If you just need to overhear packets and don't need the normal operation things and simpler. You can use SenSniff then.

GetKeyState doesn't register if holding ctrl

Given this statement:
if (GetKeyState(VK_CAPITAL) & 0x8000)
{
cout << "caps lock" << endl;
}
It works fine if I press caps lock alone, or along with any key except ctrl. I was thinking it's because ctrl is a modifier, but this works fine when holding shift. Is there something I'm missing?
GetKeyState() provides the synchronized state of the keyboard. The state of all the keys when the key was pressed. It can take a while before your program sees it, Windows provides type-ahead, so it is important that the state of all keys is known to reliably detect whether Shift, Alt, Ctrl were down at the time.
The synchronized state gets updated when you call GetMessage(). Done in the boilerplate message loop of a Windows program.
But since you use cout, you probably wrote a console mode program and don't use a message loop at all. So it doesn't update. And you'll have to use GetAsyncKeyState(). No buffering at all, so you have to call it often. Do note that the console also has a way to retrieve keystrokes with buffering supported. Probably what you really want/should do when you write code like this. Watch out for input redirection.

raw input handling (distinguishing secondary mouse)

I was writing some pices in winapi's raw input
It seem to working though I am not sure how reliable (unfaliable) it is
(and if it will be working on all systems machines etc, this is a bit worry)
also there appears many question, the one is
I would like to use my first (I mean normal/base mouse) in old way,
it is processint WM_MOUSEMOVE etc and moving arrow cursor, only the
secondary mouse I need processing by raw_input (primary can stay untouched by rawinput), the problem is
1) how can i be sure which mouse detected by rawinput is the
secondary?
2) the second mouse moves also my arrow -cursor, if I disable
it by RIDEV_NOLEGACY then both are not moving cursor (it bacame hourglass) and it is wrong too
think maybe i should setup it a bit differently my setrup rawinput function is like
void SetupRawInput()
{
static RAWINPUTDEVICE Rid[1];
Rid[0].usUsagePage = 0x01;
Rid[0].usUsage = 0x02;
Rid[0].dwFlags = 0; // Rid[0].dwFlags = RIDEV_NOLEGACY; /
Rid[0].hwndTarget = NULL;
int r = RegisterRawInputDevices( Rid, 1, sizeof(Rid[0]) );
if (!r) ERROR_EXIT("raw input register fail");
}
how to resolve this issueas andmake it work? tnx
I don't know if my approach is the best one, or not, but this is how I do it for the first item in your question:
When I process WM_INPUT using GetRawInputData(...), I check to see if the device handle passed back by the RAWINPUTHEADER structure (contained within the RAWINPUT structure returned from the function) is the same as the device I want to use. If it is not, then I simply don't bother sending back data, if it is, I then process the RAWINPUTMOUSE data returned in the RAWINPUT struct.
And if you're wondering how to get the list of devices, you can use GetRawInputDeviceList(...), which will return the device handles of the mice you're trying to work with.
As I said, this may not be the best way, but I have confirmed that it does work for my purposes. I also do this for my keyboard raw input data as well.
As for item #2, it seems likely that it affects both mice because Windows has exclusive access to the mice, so you can't register one specific mouse without registering them all with the same flags. But someone with more knowledge than I could probably give a better explanation.

Which is the Virtual Key in Mac for the Eject Key

I would like to remap the Mac Eject Key into Insert, in particular for emulating Ctrl+Insert, Alt+Insert, Shift+Insert and other common key combinations in Windows applications.
Which is the Virtual Key code for the Eject Key? I found some virtual key tables, but for some reason the Eject Key is never included.
Q: Which is the Virtual Key in Mac for the Eject Key?
A: None.
With reference to HID Usage Tables for Universal Serial Bus, Eject is not a keypress but actually a HID Usage - a One Shot Control from the Consumer Usage Page.
3.4.1.4 One Shot Control (OSC)
A One Shot Control is a push button that triggers a single event or action. A One Shot Control is encoded into a 1-bit
value and declared as a Relative, Preferred, Main item with a Logical Minimum and Logical Maximum of 0 and 1,
respectively. A 0 to 1 transition initiates an event. Nothing occurs on a 1 to 0 transition but it is required before another
event can occur. An example is degauss.
On the Consumer Usage Page (0x0C) the Eject Usage ID is defined as:
Usage ID
Usage Name
Usage Types
Section
B8
Eject
OSC
15.7
If you were wanting to fake an Eject keypress from a USB HID-capable Arduino, such as the Leonardo, you could do so with the following code which sends a Control-Shift-Eject to lock the screen...
// NicoHood's HID-Project
#include "HID-Project.h"
void setup() {
// Make pin 2 an input and turn on the pull-up resistor
// so it goes high unless connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
// Sends a clean report to the host.
// This is important on any Arduino type.
Consumer.begin();
}
void loop() {
// Control-Shift-Eject locks the screen
if (digitalRead(2) == LOW) {
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_SHIFT);
// This is a One Shot Command so doesn't need a "release"
Consumer.write(HID_CONSUMER_EJECT);
// Debounce
delay(100);
while (digitalRead(2) == LOW)
delay(100);
// Release Control-Shift keys
Keyboard.releaseAll();
}
}
As to reacting to an Eject keypress from Windows, unless it's raised as one of the Media Control-related WM_ events I expect you'll have to write a USB HID/ACPI driver that detects and raises the OSC itself.
There is Sample buttons in ACPI for device running Windows 10 desktop editions which demonstrates capturing some of the other OSCs from the Consumer page (such as Volume Increments/Decrements), you could probably expand upon this to include Eject.
Sorry I can't be of more help there, but hopefully this points you in the right direction.
I know that question has been made years ago, but maybe some people are still looking for that answer and will end up finding that question so...
Line 1805 of VoodooPS2Keyboard.cpp from VoodooPS2Controller by RehabMan says that the virtual key on Mac for the Eject Key is 0x92.
Reference:
https://github.com/RehabMan/OS-X-Voodoo-PS2-Controller/blob/master/VoodooPS2Keyboard/VoodooPS2Keyboard.cpp

How can I increase the key repeat rate beyond the OS's limit?

I have a bad habit of using the cursor keys of my keyboard to navigate source code. It's something I've done for 15 years and this of course means that my navigating speed is limited by the speed of the keyboard. On both Vista and OS X (I dual boot a MacBook), I have my key repeat rate turned all the way up. But in Visual Studio, and other apps, the rate is still much slower than I would prefer.
How can I make the key repeat rate faster in Visual Studio and other text editors?
In Windows you can set this with a system call (SystemParametersInfo(SPI_SETFILTERKEYS,...)).
I wrote a utility for myself: keyrate <delay> <repeat>.
Github repository.
Full source in case that link goes away:
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
BOOL parseDword(const char* in, DWORD* out)
{
char* end;
long result = strtol(in, &end, 10);
BOOL success = (errno == 0 && end != in);
if (success)
{
*out = result;
}
return success;
}
int main(int argc, char* argv[])
{
FILTERKEYS keys = { sizeof(FILTERKEYS) };
if (argc == 1)
{
puts ("No parameters given: disabling.");
}
else if (argc != 3)
{
puts ("Usage: keyrate <delay ms> <repeat ms>\nCall with no parameters to disable.");
return 0;
}
else if (parseDword(argv[1], &keys.iDelayMSec)
&& parseDword(argv[2], &keys.iRepeatMSec))
{
printf("Setting keyrate: delay: %d, rate: %d\n", (int) keys.iDelayMSec, (int) keys.iRepeatMSec);
keys.dwFlags = FKF_FILTERKEYSON|FKF_AVAILABLE;
}
if (!SystemParametersInfo (SPI_SETFILTERKEYS, 0, (LPVOID) &keys, 0))
{
fprintf (stderr, "System call failed.\nUnable to set keyrate.");
}
return 0;
}
On Mac OS X, open the Global Preferences plist
open ~/Library/Preferences/.GlobalPreferences.plist
Then change the KeyRepeat field. Smaller numbers will speed up your cursor rate. The settings dialog will only set it to a minimum of 2, so if you go to 0 or 1, you'll get a faster cursor.
I had to reboot for this to take effect.
Many times I want to center a function in my window. Scrolling is the only way.
Also, Ctrl-left/right can still be slow in code where there are a lot of non-word characters.
I use keyboardking also. It has a couple of isssues for me though. One, it sometimes uses the default speed instead of the actual value I set. The other is sometimes it ignores the initial delay. I still find it very useful though. They said 4 years ago they would release the source in 6 months... :(
Ok, on the suggestion of someone that modified HCU\...\Keyboard Response, this works well for me.
[HKEY_CURRENT_USER\Control Panel\Accessibility\Keyboard Response]
"AutoRepeatDelay"="250"
"AutoRepeatRate"="13"
"BounceTime"="0"
"DelayBeforeAcceptance"="0"
"Flags"="59"
Windows standard AutoRepeat delay.
13 ms (77 char/sec) repeat rate.
flags turns on FilterKeys?
These values are read at login. Remember to log out and back in for this to take effect.
For Windows, open regedit.exe and navigate to HKEY_CURRENT_USER\Control Panel\Keyboard. Change KeyboardSpeed to your liking.
I'm using KeyboardKing on my PC. It's freeware and it can increase the repeat rate up to 200 which is quite enough. I recommend to set the process priority to High for even smoother moves and less "repeat locks" which happen sometime and are very annoying. With high priority, it works perfectly.
No one understands why we navigate by arrows. It's funny.
Visual Assist has an option to double your effective key movements in Visual Studio which I use all the time.
As mentioned by the hyperlogic, on Mac OS X, internally, there are two parameters dealing with the keyboard speed: KeyRepeat and InitialKeyRepeat. In the System Preferences they are mapped to the Key Repeat Rate and the Delay Until Repeat sliders. The slider ranges and the associated internal parameter values (in parenthesis) are show below. They seem to be multipliers of the 15 ms keyboard sampling interval.
Key Repeat Rate (KeyRepeat) Delay Until Repeat (InitialKeyRepeat)
|--------------------------------| |----------------------|-----------------|
slow (120) fast (2) off (30000) long (120) short (25)
0.5 char/s 33 char/s
Fortunately, these parameters can be set beyond the predefined limits directly in the ~/Library/Preferences/.GlobalPreferences.plist file. I found the following values most convenient for myself:
KeyRepeat = 1 --> 1/(1*15 ms) = 66.7 char/s
InitialKeyRepeat = 15 --> 15*15 ms = 225 ms
Note that in the latest Mac OS X revisions the sliders are named slightly differently.
I do like to work on the keyboard alone. Why? Because when you use the mouse you have to grab it. A time loss.
On the other hand sometimes it seems that every application has its own keyboard type-rates built in. Not to speak from BIOS-properties or OS-settings. So I gathered shortkeys which can be pretty fast (i.e. you are faster typing Ctrl + right(arrow)-right-right than keeping your finger on the right(arrow) key :).
Here are some keyboard shortcuts I find most valuable (it works on Windows; I am not sure about OS X):
ctrl-right: Go to the end of the previous/the next word (stated before)
ctrl-left: Go to the beginning of the previous/the word before (stated before)
ctrl-up: Go to the beginning of this paragraph
(or to the next paragraph over this)
ctrl-down: Go to the end of this paragraph
(or to the next paragraph after this)
ctrl-pos1: Go to the beginning of the file
ctrl-end: Go to the end of the file
All these may be combined with the shift-key, so that the text is selected while doing so. Now let's go for more weird stuff:
alt-esc: Get the actual application into the background
ctrl-esc: This is like pressing the "start-button" in Windows: You can
navigate with arrow keys or shortcuts to start programs from here
ctrl-l: While using Firefox this accesses the URL-entry-field to simply
type URLs (does not work on Stack Overflow :)
ctrl-tab,
ctrl-pageup
ctrl-pagedwn Navigate through tabs (even in your development environment)
So these are the most used shortcuts I need while programming.
For OS X, the kernel extension KeyRemap4MacBook will allow you to fine tune all sorts of keyboard parameters, among which the key repeat rate (I set mine to 15 ms, and it works nice).
I don't know how to accelerate beyond the limit, but I know how to skip further in a single press. My knowledge is only in Windows, as I have no Mac to do this in. Ctrl + Arrow skips a word, and depending on the editor it may just skip to the next section of whitespace. You can also use Ctrl + Shift + Arrow to select a word in any direction.
Seems that you can't do this easily on Windows 7.
When you press and hold the button, the speed is controlled by Windows registry key : HCU->Control Panel->Keyboard->Keyboard Delay.
By setting this param to 0 you get maximum repeat rate. The drama is that you can't go below 0 if the repeat speed is still slow for you. 0-delay means that repeat delay is 250ms. But, 250ms delay is still SLOW as hell. See this : http://technet.microsoft.com/en-us/library/cc978658.aspx
You still can go to Accesibility, but you should know that those options are to help disabled people to use their keyboard, not give help for fast-typing geeks. They WON'T help. Use Linux, they tell you.
I bieleve the solution for Windows lies in hardware control. Look for special drivers for your keyboards or try to tweak existing ones.
Although the question is several years old, I still come across the same issue from time to time in several different developer sites. So I thought I may contribute an alternative solution, which I use for my everyday-developer-work (since the Windows registry settings never worked for me).
The following is my small Autorepeat-Script (~ 125 lines), which can be run via AutoHotkey_L (the downside is, it only runs under Windows, at least Vista, 7, 8.1):
; ====================================================================
; DeveloperTools - Autorepeat Key Script
;
; This script provides a mechanism to do key-autorepeat way faster
; than the Windows OS would allow. There are some registry settings
; in Windows to tweak the key-repeat-rate, but according to widely
; spread user feedback, the registry-solution does not work on all
; systems.
;
; See the "Hotkeys" section below. Currently (Version 1.0), there
; are only the arrow keys mapped for faster autorepeat (including
; the control and shift modifiers). Feel free to add your own
; hotkeys.
;
; You need AutoHotkey (http://www.autohotkey.com) to run this script.
; Tested compatibility: AutoHotkey_L, Version v1.1.08.01
;
; (AutoHotkey Copyright © 2004 - 2013 Chris Mallet and
; others - not me!)
;
; #author Timo Rumland <timo.rumland ${at} gmail.com>, 2014-01-05
; #version 1.0
; #updated 2014-01-05
; #license The MIT License (MIT)
; (http://opensource.org/licenses/mit-license.php)
; ====================================================================
; ================
; Script Settings
; ================
#NoEnv
#SingleInstance force
SendMode Input
SetWorkingDir %A_ScriptDir%
; Instantiate the DeveloperTools defined below the hotkey definitions
developerTools := new DeveloperTools()
; ========
; Hotkeys
; ========
; -------------------
; AutoRepeat Hotkeys
; -------------------
~$UP::
~$DOWN::
~$LEFT::
~$RIGHT::
DeveloperTools.startAutorepeatKeyTimer( "" )
return
~$+UP::
~$+DOWN::
~$+LEFT::
~$+RIGHT::
DeveloperTools.startAutorepeatKeyTimer( "+" )
return
~$^UP::
~$^DOWN::
~$^LEFT::
~$^RIGHT::
DeveloperTools.startAutorepeatKeyTimer( "^" )
return
; -------------------------------------------------------
; Jump label used by the hotkeys above. This is how
; AutoHotkey provides "threads" or thread-like behavior.
; -------------------------------------------------------
DeveloperTools_AutoRepeatKey:
SetTimer , , Off
DeveloperTools.startAutorepeatKey()
return
; ========
; Classes
; ========
class DeveloperTools
{
; Configurable by user
autoRepeatDelayMs := 180
autoRepeatRateMs := 40
; Used internally by the script
repeatKey := ""
repeatSendString := ""
keyModifierBaseLength := 2
; -------------------------------------------------------------------------------
; Starts the autorepeat of the current captured hotkey (A_ThisHotKey). The given
; 'keyModifierString' is used for parsing the real key (without hotkey modifiers
; like "~" or "$").
; -------------------------------------------------------------------------------
startAutorepeatKeyTimer( keyModifierString )
{
keyModifierLength := this.keyModifierBaseLength + StrLen( keyModifierString )
this.repeatKey := SubStr( A_ThisHotkey, keyModifierLength + 1 )
this.repeatSendString := keyModifierString . "{" . this.repeatKey . "}"
SetTimer DeveloperTools_AutoRepeatKey, % this.autoRepeatDelayMs
}
; ---------------------------------------------------------------------
; Starts the loop which repeats the key, resulting in a much faster
; autorepeat rate than Windows provides. Internally used by the script
; ---------------------------------------------------------------------
startAutorepeatKey()
{
while ( GetKeyState( this.repeatKey, "P" ) )
{
Send % this.repeatSendString
Sleep this.autoRepeatRateMs
}
}
}
Save the code above in a text file (UTF-8), for example named "AutorepeatScript.ahk"
Install AutoHotkey_L
Double click on "AutorepeatScript.ahk" to enjoy much fast arrow-keys (or put the file into your autostart-folder)
(You can adjust the repeat delay and rate in the script, see '; Configurable by user').
Hope this helps!
On Mac, it's option-arrow to skip a word and ⌥+Shift+Arrow to select. ⌘+Arrow skips to the end or beginning of a line or the end or beginning of a document. There are also the page up, page down, home and end keys ;) Holding shift selects with those too.
Well, it might be obvious, but:
For horizontal navigation, Home (line start), End (line end), Ctrl-Left (word left), Ctrl-Right (word right) work in all editors I know
For vertical navigation, Page Up, Page Down, Ctrl-Home (text start), Ctrl-End (text end) do too
Also (on a side note), I would like to force my Backspace and Delete keys to non-repeat, so that the only way to delete (or replace) text would be to first mark it, then delete it (or type the replacement text).
Don't navigate character-by-character.
In Vim (see ViEmu for Visual Studio):
bw -- prev/next word
() -- prev/next sentence (full stop-delimited text)
{} -- prev/next paragraph (blank-line delimited sections of text)
/? -- move the cursor to the prev/next occurence the text found (w/ set incsearch)
Moreover, each of the movements takes a number as prefix that lets you specify how many times to repeat the command, e.g.:
20j -- jump 20 lines down
3} -- three paragraphs down
4w -- move 4 words forward
40G -- move to (absolute) line number 40
There are most likely equivalent ways to navigate through text in your editor. If not, you should consider switching to a better one.

Resources