How do I use CurrentCharacter in matlab? - matlab

I am trying to use the CurrentCharacter property in matlab but I don't know how it works. Could somebody give me an example? I have tried to use get(gcf,'CurrentCharacter');

Run this code and start pressing the keys on the keyboard. Observe the output on the Command Window.
f = figure;
set(f, 'KeyPressFcn', #(x,y)disp(get(f,'CurrentCharacter')))

From MATLAB documentation:
CurrentCharacter
single character
Last key pressed. MATLAB sets this property to the last key pressed in
the figure window. Use CurrentCharacter to obtain user input.
I'm not sure how you're intending to use it, but here's a simple way to demonstrate it;;
Create a figure
Click on the figure (bring it to front in the OS GUI)
Type a character (it will likely appear in your command window)
Enter kkey = get(gcf,'CurrentCharacter') in your command window
By doing this you set kkey to the first character you typed while your figure window was active.

Related

set Matlab WindowButtonDownFcn and preserve default behavior

can I manually set WindowButtonDownFcn and selectively overwrite the right or middle-click, while preserving default behavior? Ultimate goal would be to copy figure to clipboard on some click.
set(gcf,'WindowButtonDownFcn',#(src,~) disp(src.SelectionType)); %this seemingly always overwrites default behavior of figure click
I tried this with following error msgs (scroll right)
listener(gcf,'WindowButtonDownFcn',#(src,~) disp(src.SelectionType)) %Event 'WindowButtonDownFcn' is not defined for class 'matlab.ui.Figure'.
listener(get(gcf,'parent'),'WindowButtonDownFcn',#(src,~) disp(src.SelectionType)) %Event 'WindowButtonDownFcn' is not defined for class 'matlab.ui.Root'
handle(gcf).addlistener(handle(gcf),'WindowButtonDownFcn',#(src,~) disp(src.SelectionType)) %Unrecognized method, property, or field 'addlistener' for class 'matlab.ui.Figure'.
and several more permutation using handle and event.listener with no success
Tested in Matlab 2019a.
EDIT: here's a template function to use with modifiers based on matlabgui's kind answer
%copies figure to clipboard when [control]+[right-click] anywhere on figure window (and leaving default functionality intact)
figure; plot(randi(100,1,100)) %random figure
addlistener ( gcf, 'WindowMousePress', #(src,~) myFavFunc(src,[]))
function myFavFunc(src,~)
if strcmp(src.SelectionType,'alt') && numel(src.CurrentModifier)==1 && strcmp(src.CurrentModifier,'control')
print -clipboard -dmeta
disp('copied figure to clipboard')
end
end
I dont know why Matlab hide some of the events for figures, you can get a list here:
hFig = figure;
mc = metaclass(hFig);
disp ( {mc.EventList.Name}' ) ;
From that info you can then add a listener to the mouse press event:
hFig = figure;
addlistener ( hFig, 'WindowMousePress', #(src,~)disp('myCallback' ))
That will leave the standard figure callback alone, instead of the disp command get it to run a function where you look at the figure property SelectionType to determine which mouse button was pressed. You could extend it to use the CurrentModifier property to determine if Ctrl, Shift or Alt was pressed to further customise it.

detection of key press when plotting in matlab

I would like to detect pressing of key when plotting position of pendulum and getting position of pendulum to variable, when the key is being pressed. I have no idea how to do it, I tried to search, but I have not found anything helpful. I tried to use WindowKeyPressFcn callback, but I cannot find a way to use it. I tried this way:
function keyPressCallback(source,eventdata)
keyPressed = eventdata.Key;
if strcmpi(keyPressed,'space')
disp('success');
end
end
set(f,'WindowKeyPressFcn',#keyPressCallback);
But I get an error when running the script:
There is no WindowKeyPressFcn property on the Root class.
following Navan's and Cris Luengo's comments, I rearranged the script and it runs successfully for me
f = figure;
set(f,'WindowKeyPressFcn',#keyPressCallback);
plot(rand(10,2))
function keyPressCallback(source,eventdata)
keyPressed = eventdata.Key;
if strcmpi(keyPressed,'space')
disp('success');
end
end

Making the MATLAB editor or command window grab focus programmatically

When Matlab is processing code including the plot() command, Matlab will steal window focus, when plot() is processed. While many seem to find this behavior annoying, I find it useful as an alert telling me when the plot has been processed, and I can do something else while Matlab is running.
I would, however, like to have Matlab stealing window focus whenever calculations are done (Matlab being idle), and not just when I include the plot() or figure() command.
I have found a post about disabling the window stealing behavior of plot() and figure() (Inhibit Matlab Window Focus Stealing), but not on adding window stealing behavior when calculations are done. Can it be done?
To make Matlab command window get focus, you can add commandwindow after the calculations. From the documentation,
commandwindow opens the MATLABĀ® Command Window when it is closed, and selects the Command Window when it is open.
To make an existing figure get focus, you can add figure(h), where h is the figure handle. From the documentation,
figure(h) does one of the following [...]
If h is the handle or the Number property value of an existing figure, then figure(h) makes that existing figure the current figure, makes it visible, and moves it on top of all other figures on the screen. The current figure is the target for graphics output.

MATLAB: Pause program and await keypress

I am writing a program in which at some point a graph is plotted and displayed on screen. The user then needs to press 'y' or 'n' to accept or reject the graph. My current solution uses the PsychToolbox (the actual solution doesn't need to), which includes a command called 'KbCheck' which checks at the time of calling the state of all the keyboard buttons. My code looks like this:
function [keyPressed] = waitForYesNoKeypress
keyPressed = 0; % set this to zero until we receive a sensible keypress
while keyPressed == 0 % hang the system until a response is given
[ keyIsDown, seconds, keyCode ] = KbCheck; % check for keypress
if find(keyCode) == 89 | find(keyCode) == 78 % 89 = 'y', 78 = 'n'
keyPressed = find(keyCode);
end
end
The problem is, that the system really does 'hang' until a key is pressed. Ideally, I would be able to scroll, zoom, and generally interact with the graphs that are plotted onscreen so that I can really decide whether or not I want to press 'y' or 'n'!
I have tried adding 'drawnow;' into the while loop above but that doesn't work: I still am unable to interact with the plotted graphs until after I've accepted or rejected them.
The solution doesn't have to use PsychToolbox; I assume there are plenty of other options out there?
Thanks
I'd use the input function:
a = input('Accept this graph (y/n)? ','s')
if strcmpi(a,'y')
...
else
...
end
Although admittedly it requires two keypresses (y then Enter) rather the one.
Wait for buttonpress opens up a figure, which may be unwanted. Use instead
pause('on');
pause;
which lets the user pause until a key is pressed.
Why not using waitforbuttonpress instead?
Documentation: http://www.mathworks.fr/help/techdoc/ref/waitforbuttonpress.html
You don't want to use waitforbuttonpress since it locks the figure gui (no zooming, panning etc).
pause can cause the command window to steal the focus from the figure.
The solution I find to work best is to open the figure with a null keyPressFcn in order to avoid focus problems:
figure('KeyPressFcn',#(obj,evt) 0);
and then wait for CurrentCharacter property change:
waitfor(gcf,'CurrentCharacter');
curChar=uint8(get(gcf,'CurrentCharacter'));
Wait for key press or mouse-button click:
Example:
w = waitforbuttonpress;
if w == 0
disp('Button click')
else
disp('Key press')
end
for more information visit:
http://www.mathworks.com/help/matlab/ref/waitforbuttonpress.html
The waitforbuttonpress command is good but is triggered by either a mouse click or a key press. If you want it to trigger only from a key press, you can use the following hack:
while ~waitforbuttonpress
end

Matlab IMRECT backward compatibility

I've writtend a GUI function in MATLAB R2009b which makes use of the IMRECT function. I need to make sure this GUI also works in MATLAB R2007b: since this release the IMRECT function has undergone extensive changes. I have two question:
1 - in the new (R2009b) IMRECT, a method GETCOLOR is defined which allows to get the color which was selected by the user using the scroll menu. Is there a way to mimic this behavior for the old (R2007b) function?
2 - in MATLAB R2009b I can use WAIT after using IMRECT as follows:
h = imrect(axhandle);
wait(h);
this allows to wait unitl the user as correctly placed his/her rectangle and has double click to confirm the choice. Is there anything analogous that can be used with IMRECT from R2007b?
Unfortunately, you need a workaround for both functions.
Here is one way to do it:
%# Create a figure and some points
fh = figure;plot(rand(10,1),rand(10,1),'.')
ah = gca;
%# this allows the user to place the rectangle. However, the code resumes
%# as soon as the rectangle has been drawn
rh = imrect(ah,[]);
%# Create a dialog to have the possibility to uiwait
wh = warndlg('Please close this dialog once you are done adjusting your rectangle');
uiwait(wh)
%# Get the color of the rectangle
rectKids = get(rh,'Children');
rectangleColor = get(rectKids(1),'Color');
You can use verLessThan to check for the Matlab version in order to get the proper functionality. However, if there are users who'll use the code both on 2007b and 2009b, I suggest you leave the dialog box in for everyone, so that they don't get confused when they switch.