"RETURN" 按键使用 "CurrentCharacter" returns 空字符串
"RETURN" key press using "CurrentCharacter" returns an empty string
我正在尝试编写一个 GUI,用户必须在其中从键盘输入命令(RETURN 或 DELETE)。为此,我编写了一段代码,其中设置了 'KeyPressFcn' 以读取用户按下的键。主要问题是,当用户键入 "RETURN" 或 "DELETE" 时,我得到的只是一个空字符串。
代码如下:
function getKey(axeshandle)
fig = ancestor(axeshandle, 'figure');
set(fig, 'KeyPressFcn', @keyRead);
uiwait(fig);
function keyRead(src, callback)
key = get(fig, 'CurrentCharacter');
strcmp(key, 'return')
class(key)
end
end
知道如何解决这个问题吗?
首先,你的问题是 是 return 当前字符,恰好对于 return 键,字符是回车 return 字符 (\r
),所以它看起来像一个空字符串。如果您想执行此检查,您可以直接与 \r
进行比较,或者它是 ASCII 等效项 (13).
% Use char(13) to create \r
strcmp(key, char(13))
% Convert char to it's ASCII representation and compare
isequal(double(key), 13)
% Create \r using sprintf
strcmp(key, sprintf('\r'))
同样,删除键 return 是 delete (ASCII 127)。
您可以通过将当前字符转换为数字(它是 ASCII 表示)来检查这一点
double(get(src, 'CurrentCharacter'));
更好的选择
与其尝试获取当前图形的 CurrentCharacter
,不如使用回调的第二个输入(事件数据)来确定按下了哪个键。
function keyRead(src, evnt)
% Access the Key field from the event data
key = evnt.Key;
% Compare the value with "return"
strcmp(key, 'return')
% Comapre the value with delete
strcmp(key, 'delete')
end
我正在尝试编写一个 GUI,用户必须在其中从键盘输入命令(RETURN 或 DELETE)。为此,我编写了一段代码,其中设置了 'KeyPressFcn' 以读取用户按下的键。主要问题是,当用户键入 "RETURN" 或 "DELETE" 时,我得到的只是一个空字符串。
代码如下:
function getKey(axeshandle)
fig = ancestor(axeshandle, 'figure');
set(fig, 'KeyPressFcn', @keyRead);
uiwait(fig);
function keyRead(src, callback)
key = get(fig, 'CurrentCharacter');
strcmp(key, 'return')
class(key)
end
end
知道如何解决这个问题吗?
首先,你的问题是 是 return 当前字符,恰好对于 return 键,字符是回车 return 字符 (\r
),所以它看起来像一个空字符串。如果您想执行此检查,您可以直接与 \r
进行比较,或者它是 ASCII 等效项 (13).
% Use char(13) to create \r
strcmp(key, char(13))
% Convert char to it's ASCII representation and compare
isequal(double(key), 13)
% Create \r using sprintf
strcmp(key, sprintf('\r'))
同样,删除键 return 是 delete (ASCII 127)。
您可以通过将当前字符转换为数字(它是 ASCII 表示)来检查这一点
double(get(src, 'CurrentCharacter'));
更好的选择
与其尝试获取当前图形的 CurrentCharacter
,不如使用回调的第二个输入(事件数据)来确定按下了哪个键。
function keyRead(src, evnt)
% Access the Key field from the event data
key = evnt.Key;
% Compare the value with "return"
strcmp(key, 'return')
% Comapre the value with delete
strcmp(key, 'delete')
end