Fixed #3101: Alt+Arrow-Keys print extra characters (#3117)

## Summary of the Pull Request

This PR potentially fixes #3101.

## PR Checklist
* [x] Closes #3101.
* [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [ ] Tests added/passed
* [ ] Requires documentation to be updated
* [ ] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #xxx

## Detailed Description of the Pull Request / Additional comments

This PR fixes #3101 by setting flag 0 in `ToUnicodeEx()` even though the documentation says "If bit 0 is set, a menu is active.". I'm not 100% sure why it works, but it definitely does in this case.
I thought that bit 2, which claims that "keyboard state is not changed" would be sufficient to prevent this from happening, but it seems that's not the case.

I believe this PR should be verified by a developer at Microsoft who's familiar with the internal workings of `ToUnicodeEx()`.
We need this function (or something similar) to translate Alt+Key combinations to proper unicode.
But at the same time it should not send us any additional IBM-style Alt Codes to our character handler if that translation fails (and `ToUnicodeEx()` returns 0).

## Validation Steps Performed

See #3101 for more information. I ensured that Alt+Arrow-Key combinations do not print ◘☻♠♦ anymore.
This commit is contained in:
Leonard Hecker 2019-11-13 17:59:28 +01:00 committed by Mike Griese
parent 1177815f81
commit c9f148c4b6

View file

@ -307,13 +307,19 @@ wchar_t Terminal::_CharacterFromKeyEvent(const WORD vkey, const WORD scanCode, c
keyState[VK_CONTROL] = states.IsCtrlPressed() ? 0x80 : 0;
keyState[VK_MENU] = states.IsAltPressed() ? 0x80 : 0;
// For the following use of ToUnicodeEx() please look here:
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-tounicodeex
// Technically ToUnicodeEx() can produce arbitrarily long sequences of diacritics etc.
// Since we only handle the case of a single UTF-16 code point, we can set the buffer size to 2 though.
constexpr size_t bufferSize = 2;
wchar_t buffer[bufferSize];
// wFlags: If bit 2 is set, keyboard state is not changed (Windows 10, version 1607 and newer)
const auto result = ToUnicodeEx(vkey, sc, keyState, buffer, bufferSize, 0b100, nullptr);
// wFlags:
// * If bit 0 is set, a menu is active.
// If this flag is not specified ToUnicodeEx will send us character events on certain Alt+Key combinations (e.g. Alt+Arrow-Up).
// * If bit 2 is set, keyboard state is not changed (Windows 10, version 1607 and newer)
const auto result = ToUnicodeEx(vkey, sc, keyState, buffer, bufferSize, 0b101, nullptr);
// TODO:GH#2853 We're only handling single UTF-16 code points right now, since that's the only thing KeyEvent supports.
return result == 1 || result == -1 ? buffer[0] : 0;