Delphi VirtualKey to WideString

I would like to convert a virtual key to a WideString. That's what I have so far...

function VKeytoWideString (Key : Word) : WideString;
var
 WBuff         : array [0..255] of WideChar;
 KeyboardState : TKeyboardState;
 UResult       : Integer;
begin
 GetKeyBoardState (KeyboardState);
 UResult := ToUnicode(key, MapVirtualKey(key, 0), KeyboardState, WBuff, 0,0);
 Result  := WBuff;
 case UResult of
  0 : Result := '';
  1 : SetLength (Result, 1);
  2 :;
  else
   Result := '';
 end;
end;

it always returns 0 but why? Please help.


You are setting the cchBuff parameter of ToUnicode() to 0 instead of the actual buffer size, so the function cannot store any characters it translates.

Try this instead:

function VKeytoWideString (Key : Word) : WideString; 
var 
  WBuff         : array [0..255] of WideChar; 
  KeyboardState : TKeyboardState; 
  UResult       : Integer;
begin 
  Result := '';
  GetKeyBoardState (KeyboardState); 
  ZeroMemory(@WBuff[0], SizeOf(WBuff));
  UResult := ToUnicode(key, MapVirtualKey(key, 0), KeyboardState, WBuff, Length(WBuff), 0); 
  if UResult > 0 then
    SetString(Result, WBuff, UResult)
  else if UResult = -1 then
    Result := WBuff;
end; 
链接地址: http://www.djcxy.com/p/61492.html

上一篇: Delphi 7中的Widestring到字符串转换

下一篇: Delphi VirtualKey转换为WideString