Written by LogicKills

download Written by LogicKills

of 10

Transcript of Written by LogicKills

  • 8/7/2019 Written by LogicKills

    1/10

    /*Written by LogicKills;

    This program incorporates my,mouse-coordinate program, and mytimer program and combines them tomake a program to click an objectfor x amount of time.

    Have fun with it! And remember,Head over to logickills.org for more!!

    http://forum.codecall.net/classes-code-snippets/10581-turn-monitor-

    off.htmlhttp://forum.codecall.net/classes-code-snippets/11413-c-mouse-coor.html

    */

    #include #include

    int main(){

    const int SEC = 20; // put how many seconds you want to click..const int CURSOR_X = 200; // x-coordinate of mouseconst int CURSOR_Y = 144; // y-coordinate of mouse

    SetCursorPos(CURSOR_X,CURSOR_Y);

    clock_t delay = SEC *CLOCKS_PER_SEC;clock_t start = clock();while(clock() - start < delay){

    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);}

    return 0;}

  • 8/7/2019 Written by LogicKills

    2/10

    Cornell University

    BioNB 441

    Graphical User Interface Design

    Introduction

    Once you have written a program to perform some data-related function you may find that otherpeople want to use it. It is useful to wrap a GUI around the function so that other people (and

    yourself) can remember how to use the program. MatLab supplies a set of tools for building GUIelements including:

    y Control widgetso Buttons

    A pushbutton is typically used whenyou want an immediate action to occur when the user presses

    the button. An example might be a button to quit theapplication.

    A checkbox is used when youneed to specify a persistent binary condition. An

    example might be to turn on/off the grid associated with the axes of a plot.

    A radio button is typically usedwhen you need to group several buttons together so that

    the group of buttons have mutually exclusive settings.An example might be a choice among several colors of a plot.

    o Text areas Editable text may be modified by

    the user by clicking the field and typing. An editabletext field seems to be limited to one line. You could use

    an editable field to allow the user to enter a function to be plotted.

    Noneditable text may be changedby the program, but not directly by the user. You might

    use this for labels or instructions to the user.

  • 8/7/2019 Written by LogicKills

    3/10

    o A slider is used to set a numerical valuein a definedrange. Clicking in the body of the slider

    moves the slider about 10% by default. Clicking in theend-arrows moves it 1%. Dragging the bar changes the slidervalue.

    o A listbox allows the user to choose betweenseveral items. In many ways it is like a radiobutton. One and

    only one item is chosen at a time. If there are too many items tofit in the frame, then scrollbars automatically appear.

    o A

    frame is a decorative device with no actualfunction except visual grouping of other controls.

    y Menus/submenuso Window menus are the typical menus that appear by default at the top of all

    Matlab figure windows (except on Macintosh computers). You can define yourown and add to or replace the existing menus.

    o Popup menus are really a uicontrol like a listbox, except you can only see thecurrent selection, unless you click on the popup menu.

    o

    Context menus are associated with specific objects. Right-clicking on an objectwith an associated context menu pops up the menu. The second example below

    implements a contex menu.y Drawing regions defined as typical Matlab axes.y Dialog boxes may be defined to help the user navigate complicated choices or to give the

    user information. The second example below implements several dialog boxes. Possible

    dialog boxes include:o erroro helpo inputo questiono file read/write

    The various GUI elements have a lot of automatic behavior programmed in. For instance, theslider element has built-in behaviors for dragging the slider, clicking in the body of the slider (to

    make a big change in value), and clicking in the end-arrows of the slider (to make a smallchange). Your program must specify what to do with the value returned by the slider element.

    The following code fragment implements a slider in a figure window. The main uicontrol

    function would be executed once to define the control. The Callback parameter is a vector of

  • 8/7/2019 Written by LogicKills

    4/10

    strings which defines what happens each time the user manipulates the slider. In this simpleexample, the slider value is assigned to a variable and printed in the command window. The

    variable slider1 is refered to as the handle to the control. The callback string refers to slider1to retrieve the value from the control handle.

    slider1=uicontrol(gcf,...'Style','slider',...

    'CallBack', ...['s1value=get(slider1,''value'');',...

    'disp (num2str(s1value));'...]);

    The slider appearance and function can be controlled by changing its properties. The following

    code sets up the slider to a value-range of [-20 20], sets its position, initial value, color, and thestep size for clicks in the slider body and in the slider ends.slider1=uicontrol(gcf,...

    'Style','slider',...'Min' ,-20,'Max',20, ...

    'Position',[10,220,150,20], ...'Value', 10,...'SliderStep',[0.01 0.1], ...'BackgroundColor',[0.8,0.8,0.8],...'CallBack', ...['s1value=get(slider1,''value'');',...

    'disp (num2str(s1value));'...]);

    As with any graphics object in Matlab, a list of the object's current properties may be obtained by

    typing get(uihandle), or specifically for the slider above get(slider1). A list of all possible

    property settings may be obtained by typing set(uihandle), or specifically for the sliderset(slider1).

    Usually when you write code in a procedural language like Matlab, you expect execution to

    proceed linearly through the program (except for loops and subroutine calls that you program).Writing a program with uicontrols is different in several ways:

    y The controls you define are 'owned' by a figure and persist even when there is no matlabscript running. The controls disappear if you close or clear the figure. The visual state ofeach uicontrol, for example the position of a slider, is maintained in the figure and not in

    the Matlab workspace. Butthe handle to the uicontrol (and its data) may be in the Matlab

    workspace. This means that if you type clear all when you have uicontrols in a figure,that the control will still be visible, but you may no longer get its value. The complicated

    data storage relationship between the figure and the workspace leads to lots of frustrationfor new programmers. Approaches to handling this complexity are explained in the

    examples below.y Each uicontrol (slider, button, menu) has a chunk of code which defines it. This code is

    only executed once for each control. The 'callback code' is not executed when theuicontrol is defined.

  • 8/7/2019 Written by LogicKills

    5/10

    y Each uicontrol (slider, button, menu) may have a chunk of 'callback code' associated withit. When a control is manipulated, this chunk of code executes.

    Examples

    1. There is a tutorial and short example of a GUI written by Doug Schwarz at servtech.com.This tutorial explains a very clever way of packaging a GUI design so that all the

    functions of the design are in one Matlabfunction file. The tutorial shows how to handlethe complicated data-storage relations mentioned in the introduction. All data is stored in

    the Figure object and none in the Matlab workspace.2. I attempted to use most of the different types of uicontrols shown in the introduction in

    one demo. There is a window menu, a pop-up menu, a context menu attached to the plotline, several types of pushbuttons, a slider, dialog boxes, and an edit field. The Matlab

    code is clean, but the visual appearance is amazingly ugly because I spent no time with

    visual design.3. The simple equation plotter, shown below, can be constructed with about a page ofMatlab code. The code consists of the definitions of five UI controls, including

    pushbuttons, editable text, and static text. All the dynamics of the code are controlled bydefault UI control functions and callback properties for two of the pushbuttons. A less

    elegant (but perhaps clearer)program uses an event-loop to detect mouse clicks. Thecallback code in each control merely sets a flag which is tested in the main event-loop.

    4. There is a longer example which computes the classical Hodgkin-Huxley response of asquid axon to a user-setable current. The actual solver routine included in this examplewas written forPhysiology 317 - Methods in Computational Neurobiology (UIUC) by M.

    Nelson. The figure window generated by the example code is shown below (click on itfor more detail). A modified version of the Hodgkin-Huxley example uses Matlab ODE

    solver routines and has a few small GUI enhancements, but requires a separate functionfile for the integrator.

  • 8/7/2019 Written by LogicKills

    6/10

    5. A student and I used a modeling system to build a simple maze. The maze was presentedas both an overhead and in-the-maze view. We made a simple GUI to navigate the maze.

    There are two files necessary to run this example; maze6.m and maze6key.m. The firstprogram defines the maze and a bunch of UIcontrols. The second program is a function

    which is called to implement camera movement through the maze. You must alsodownload the modeling system programs. An example of the two views is shown below.

    6. This example is a minimal user interface which allows a user to click on a plotted curveand read back the index of the plotted point nearest to the mouse click. Such a functionmight be useful for a parametric plot where x(t) and y(t) and you want to get t from the

    plot. The following code uses the window button function to detect a mouse-down eventand a uicontrol to stop the point-aquisition loop.

    7. clf8. clear all

  • 8/7/2019 Written by LogicKills

    7/10

    9.10.11. %plot a couple of sine curves to click on12. x = 0:.1:6.28;13. y = sin(x);14. hline1=plot(x,y);15. hold on16. hline2=plot(x,-y/2+.4);17.18.19. %the mouse-click sets a flag for point aquisition20. set(gcf,'windowbuttondownfcn','hit=1;');21.22. %make a control to stop the loop23. uicontrol('style','pushbutton',...24. 'string','Quit', ...25. 'position',[0 0 50 20], ...26. 'callback','stopit=1;');27.28.29. %start looping and waiting for a mouse click30. stopit=0;31. while (stopit==0)32.33. %check for valid object and chek for line 134. %and see if the mouse was clicked35. if ~isempty(gco) & gco == hline1 & hit==136.37. %get the mouse position in graph units38. mouse = get(gca,'currentpoint');39.40. %calculate the point nearest to the41. %mouse click42. [val, pnt] = ...43. min( sqrt(...44. (get(hline1,'xdata')-mouse(1,1)).^2 ...45. +(get(hline1,'ydata')-mouse(1,2)).^2 ...46. ));47.48. %display the result49. disp(['line1 point=',num2str(pnt)])50.51. %wait for the next click52. hit=0;53. end54.55. %check for valid object and chek for line 256. %and see if the mouse was clicked57. if ~isempty(gco) & gco == hline2 & hit==158.59. mouse = get(gca,'currentpoint');60.61. [val, pnt] = ...62. min( sqrt(...63. (get(hline2,'xdata')-mouse(1,1)).^2 ...64. +(get(hline2,'ydata')-mouse(1,2)).^2 ...65. ));

  • 8/7/2019 Written by LogicKills

    8/10

    66.67. disp(['line2 point=',num2str(pnt)])68. hit=0;69. end70.71. drawnow72. end73.This example builds on the last example to make a editable spline curve with a user-

    selected number of control points. Clicking anywhere on the figure moves the nearestcontrol point to that vertical position.

    74. clf75. clear all76. set(gcf,'doublebuffer','on')77.78. tmax = 2 ; % seconds.79. NumControl = 20 ; %number of control points80. FPS = 30 ; %frames/sec81. ForceZeroSlope = 1 ;82. AngleRange = 90 ;83.

    84. t = linspace(0, tmax, NumControl) ;85. tt = linspace(0, tmax, tmax*FPS) ;86. %start with all zeros in control points87. y = zeros(1,length(t));88.89. if ForceZeroSlope90. cs = spline(t,[0 y 0]);91. else92. cs = spline(t,y);93. end94. yy = ppval(cs,tt);95.96. hold on97. sp = plot(tt,yy);98. line1 = plot(t,y,'or');99. set(gca, 'ylim', [-AngleRange AngleRange])100.%set(gca, 'position', [0 0 1 1])101.102.%the mouse-click sets a flag for point aquisition103.set(gcf,'windowbuttondownfcn','mousedown=1;');104.set(gcf,'windowbuttonupfcn','mouseup=1;');105.set(gcf,'windowbuttonmotionfcn','mousemotion=1;');106.107.%make a control to stop the loop108.uicontrol('style','pushbutton',...109. 'string','Quit', ...110.

    'position',[0 0 50 20], ...111. 'callback','stopit=1;');

    112.113.%start looping and waiting for a mouse click114.stopit = 0;115.mousedown = 0;116.mouseup = 0;117.mousemotion = 0;118.119.while (stopit==0)

  • 8/7/2019 Written by LogicKills

    9/10

    120.121. %check for valid object and chek for line 1122. %and see if the mouse was clicked123.124. if mousedown==1125.126. %get the mouse position in graph units127. mouse = get(gca,'currentpoint');128. %calculate the point nearest to the129. %mouse click130. lineX = get(line1,'xdata');131. lineY = get(line1,'ydata');132. [val, pnt] = min(abs(lineX-mouse(1,1)));133.134. %move the control point on the plot135. lineY(pnt) = mouse(1,2);136. set(line1, 'ydata', lineY);137.138. %make new spline139. if ForceZeroSlope140. cs = spline(t,[0 lineY 0]);141. else142. cs = spline(t,lineY);143. end144. yy = ppval(cs,tt);145. set(sp, 'ydata', yy);146.147. %wait for the next click148. if mouseup == 1149. mouseup = 0;150. mousedown = 0;151. mousemotion = 0;152. end153. end154.155. drawnow156.end157.close

    158. The following code fragment can be used to measure distances in an axes context.A window button-down event causes a point to be stored and a dragbox to be drawn as avisual reference. A window button-up event stores the current mouse point and calculates

    a distance in axes units. This fragment might be located at the beginning of a program tobe used for data capture later.

    159.set(gcf,'WindowButtonDownFcn',...160. ['initialpt=get(gca,''currentpoint'');'...161. 'rect=rbbox;' ...162. ]);163.164.set(gcf,'WindowButtonUpFcn',...165. [...166. 'finalpt=get(gca,''currentpoint'');'...167. 'disp(finalpt(1,1)-initialpt(1,1));'...168. ]);

  • 8/7/2019 Written by LogicKills

    10/10

    Another small code fragment shows how to detect which mouse button was pushed. The

    undocumented figure property selectiontype holds the current mouse button depressed.

    The values it can contain are the strings normal, alt, extend oropen. Any button,

    when double-clicked, causes this property to return open.

    %Detecting which button is pushed.%Use:%get(gcf,'selectiontype')%Which returns:% normal | open | alt | extend%Meaning:% left button | doubleclick | right button | middle buttonfigure(1);clf;axisset(gcf,'windowbuttondownfcn', ...['disp(get(gcf,''selectiontype''));'])