Creating a graphical user interface using the Win32 API. Graphical interfaces and tools for their development. What EI to create

yadobr January 14, 2014 at 09:10

Graphical User Interface Design

  • Interfaces

Introduction

There are billions of computing devices in the modern world. Even more programs for them. And each has its own interface, which is the “levers” of interaction between the user and machine code. Not surprisingly, the better the interface, the more effective the interaction.

However, not all developers and even designers think about creating a convenient and understandable graphical user interface.

For myself, I started by asking questions: general principles, what interface elements (EI) create what design they should have, where they should be placed correctly and how they should behave.
Below I will try to answer these questions.

General principles


What EI should I create?


What should the EI design be?

In fact, EI design is the topic of a separate article. Here you need to take into account everything: from color, shape, proportions, to cognitive psychology. However, a few principles are still worth noting:

How to correctly position the EI on the screen?


How should EIs behave?


In custody

This article does not claim to be the most comprehensive guide to interface design principles. Graphical user interface is a vast topic, closely intertwined with psychology, occupying the minds of scientists and hundreds of pages of books and studies. In such a small format, there is no way to express the fullness of the topic raised. However, following the basic principles will make it possible to build interfaces that are more user-friendly, as well as simplify the design process itself.
Thank you for your attention.

Literature

Jeff Raskin, “Interface: new directions in the design of computer systems”
Alan Cooper, “About the interface. Fundamentals of Interaction Design"
Alan Cooper, “Mental hospital in the hands of patients”

Send your good work in the knowledge base is simple. Use the form below

Good work to the site">

Students, graduate students, young scientists who use the knowledge base in their studies and work will be very grateful to you.

Posted on http://www.allbest.ru/

Posted on http://www.allbest.ru/

FEDERAL EDUCATION AGENCY OF THE RF

State educational institution

higher professional education

Russian State Humanitarian university

Institute of Information Sciences and Security Technologies

Department of General Informatics

TEST

IN INFORMATION TECHNOLOGY

GRAPHIC INTERFACES AND THEIR DEVELOPMENT TOOLS

Lisichenok Konstantin Viktorovich

Externship 3 years of study

(4-year duration of study)

Group b (information sphere)

Scientific adviser,

Ph.D., teacher: Mashintsov E.A.

Moscow 2005

Plan

Introduction

X Window System

General system structure X Window

Programming using the X Toolkit Intrinsic (Xt) library

Xt objects, their classification

Information sources

Introduction

When, for the first time in 1959, at the UNESCO conference on information processing, Streci proposed a time-sharing mode for solving problems on computers, from that moment it was customary to count the beginning of interactive computing and, consequently, the study of the human-machine interface. As computer power increased, so did the cost of the conversational component of the software. The issue of machine efficiency has become more acute with the rapid entry into the market of workstations that combine interactivity with graphics. The term efficiency has since changed its meaning - if previously it reflected such characteristics as processor time and the amount of memory occupied, now it is understood as ease of development, ease of maintenance and ease of working with the program. Therefore, the cost of researching and developing the user interface is justified.

The development of any application software usually involves the creation of a user interface. Since most modern user interfaces are based on similar ideas (active use of the mouse, focus on objects, graphics, etc. - imitation of processes and phenomena, the ability to use algorithms familiar to every person from his everyday life), there is an opportunity and necessity development of auxiliary software designed to create such “standard” interfaces, or rather their bases.

On the other hand, the multiplicity and variety of hardware and system platforms on which this software will need to run requires its portability at the level source code. The above requirements logically lead to the idea of ​​a portable, unified software toolkit for creating user interfaces or, if we consider the final application software, a system (module, block) that manages (manages, manages, maintains, manages) the interface with the user.

You can classify such tools (User Interface tools) according to the following scheme:

* Text screen systems (curse, ncurse, etc).

* Graphic screen systems.

* Multi-window systems (WMS):

* character-oriented (text);

* graphic;

*UI toolkits

* traditional;

* object-oriented;

* UIDS - User Interface Development System - user interface development system (toolkit);

* UIMS - User Interface Management System - user interface (management) system (software module - an integral part of the final product in conjunction with the corresponding UIDS);

* UIDE - User Interface Development Environment - user interface development environment.

This scheme does not pretend to be a systematic classification; rather, it is simply an enumeration.

Currently, great efforts are being made to develop methods and create tools within systems called UIMS - User Interface Management System.

SystemX Window

X Window or simply X is a system for creating a graphical user interface, initially on computers running UNIX. X was created at MIT (Massachusetts Institute of Technology). Currently, version 11.6 (X11R6) has already been released and preparations are actively underway for the release of version 7.

A special feature of X Window is its architecture - it is built according to the client-server scheme. The interaction between the X client and the X server occurs within the framework of the appropriate protocol application level- X-protocol. X Window is indifferent to the transport used, which can be either a local UNIX-socket or any network one, for example, TCP. This means that the X client and X server can “live” on different computers, i.e. the program can perform input/output of graphical information on the screen of another computer, and differences in the architecture of the X client and X server do not play any role - this is ensured by the X protocol standard. The system provides graphical output to the machine screen, receives signals from input devices such as the keyboard and mouse, and transmits them to programs. It should be noted that the output device may have more than one screen. X provides output to any of them. All this: screen (screens), input devices (keyboard, mouse) is called in X Window terms - display.

Thanks to its architecture, X Window can be freely used in distributed computing systems, for example, in TCP/IP networks (Internet).

X allows the user (behind the display) to communicate with many programs simultaneously. To prevent the output from them from being mixed, the system creates “virtual subscreens” - windows - on the display screen. Each application (as a rule) draws only in its own window (or windows). X provides a set of tools for creating windows, moving them around the screen, resizing them, displaying them, and so on.

As a rule, programs have a set of configuration parameters - resources. It could be the color of the window, various parameters text font (ligature, size, etc.) and much more. The system standardizes the way of defining application resources, managing them, and contains a number of procedures for working with them. This set of functions is called the “resource manager” (Xrm - X resource manager). The "storage" of program parameters is called the resource database.

X operates according to the ideology of event-driven architecture - it organizes communication between the programs themselves and between programs and the external environment through events. An event is a unit of information that identifies changes or actions occurring in a system. Using the event identifier, you can obtain information about it - the type of event, its characteristics, where it occurred, etc.

General X Window Device

System X Window is a collection of programs and libraries. Its "heart" is special program- X server. This is a separate UNIX process that takes place on the computer to which the display is attached. It is the server that knows the features of specific equipment, knows what needs to be done to display any graphic object, for example, a primitive, to the screen. He can also perceive and process signals coming from the keyboard and mouse.

The server communicates with client programs by sending or receiving data packets from them. If the server and client are on different machines, then the data is sent over the network, and if on the same machine, then the internal channel is used. For example, if the server detects that the user has pressed the mouse button, then it prepares the corresponding packet (event) and sends it to the client in whose window the mouse cursor was at the moment the button was pressed. And vice versa, if the program needs to display something on the display screen, it creates the necessary data packet and sends it to the server. Obviously, a description of this interaction, packet formats, etc. and compiles the specification for the aforementioned X protocol.

However, to program for X, you don't need to know the details of the server implementation and the X protocol. The system provides a standard library of procedures by which programs access X services "at a high level." So, in order to display a point on the screen, it is enough to call the corresponding standard procedure, passing it the required parameters. This procedure will do all the work of generating data packets and transmitting them to the server.

X window

As mentioned earlier, a window is a basic concept in X. It represents, typically, a rectangular area on the screen that the system provides to a client program. The latter uses a window to display graphical information.

The window has an inside and an edge. The main attributes of a window are the width and height of the interior, as well as the width (thickness) of the edge. These parameters are called window geometry.

Each window is associated with a coordinate system, the origin of which is in the upper left corner of the window (more precisely, its interior). The x-axis points to the right and the y-axis points down. The unit of measurement on both axes is pixel.

X Window allows a program to create multiple windows at the same time. They are linked into a hierarchy in which some are “parents” and others are “descendants”. The server itself creates one main window on each screen, which is the topmost “parent” of all other windows. This window is called the "root" window.

Window management

Windows can be placed on the screen randomly, overlapping each other. X Window has a set of tools, using which the client program can change the size of windows and their position on the screen. A special feature of the system is that it does not have a built-in ability to control windows using the mouse or keyboard. To make this possible, you need special client- window manager.

However, a manager cannot correctly manage windows without knowing anything about them. Windows can have various properties that the window manager must provide: for example, in many cases it is convenient to have window titles, in others it is desirable that the window cannot be made smaller, or vice versa - larger, of a certain size. The window can be "collapsed" into an icon ("icon") - in this case the manager must know which icon to use and what to name it. Clients can communicate their wishes regarding windows to the manager in two ways:

* when creating a window X, “hints” can be transmitted about the initial position of the window, its geometry, minimum and maximum sizes, etc.;

* you can use the built-in way of communication between programs in X - the “properties” mechanism.

X Window Graphics Features

The X Window System is designed to run on raster displays. The number of bits per pixel is called the depth or thickness of the display. Bits with the same numbers (the same binary digits) in all pixels form a kind of plane, as if parallel to the screen. It is called the color plane. X allows you to paint in any color plane(s) without affecting the others.

The pixel value does not directly set the color of a point on the screen, but sets the number of the cell in a special array in which the color value is stored, i.e. the pixel value specifies the color number in the current palette.

X has a large set of procedures that allow you to draw graphic primitives: points, lines, arcs, text; work with free-form areas.

"Properties" and atoms

X Window has built-in facilities for providing information between client programs. To do this, the “properties” mechanism is used. "Property" is information structure, associated with some object, for example, a window, available to all X clients. Each property has a name and a unique identifier - an atom. Typically, property names are written in capital letters. Atoms are used to access the contents of properties in order to reduce the amount of information sent between clients and the X server.

X provides a number of procedures that allow you to translate a property name into a unique atom, and, conversely, to obtain the necessary data for an atom.

Some properties and their corresponding atoms are predefined and are created at the time of server initialization.

Programming using the libraryX Toolkit Intrinsic (Xt)

To make programming on the X window system easier, several packages have been created. The de facto standard currently is the X Toolkit Intrinsics (Xt) library, which is included in the standard delivery of the system. Xt makes it easy to initialize programs and create windows. In addition, the library contains tools for creating objects (control elements) used by programs when communicating with users. In Xt terms, the control element is called a widget.

Currently, various sets of control elements (objects) are implemented on the basis of the package, for example, Athena, OSF/Motif, Open Look. These kits, combined with Xt itself, are used as a convenient tool for creating interfaces. They take care of the tedious work that a programmer would have to do manually if he were writing his own application using only the X Window core library routines.

Xt Basics

programming user graphical interface

Xt objects

The Xt package is a base for creating control elements - widgets (blanks). In the Xt sense, a widget is simply a data structure whose fields include the ID of the element itself, the ID of its window, if any, and much more. The attributes of such an object are called resources. Widget resources can be, for example, the color of its window, the color of the window border, the font of the displayed text, etc.

Each object belongs to one of the predefined classes (widget class). A class is understood in the usual sense for object-oriented programming, i.e.: a class can be considered as a set of instances (objects) having the same characteristics. The Xt classes form a hierarchy.

During operation, the program creates the objects themselves (instances of classes - widget). They form aggregates, each of which also represents a certain hierarchy. Each such hierarchy is called an object tree (widget tree). The root of the tree is necessarily a widget, which belongs to one of the subclasses of the special class - Shell. If among two widgets A and B of a tree of objects, the first is closer to the root than the second, then A is the parent object ("parent") of B, and B is the subobject (or "child" object (child)) of A. Thus, The shell object is the parent widget of all other widgets in the tree of objects. It is he who interacts between the program and the window manager.

The described hierarchy of widgets corresponds to the relationship of their windows, which is a property of X Window. In addition, another hierarchy is imposed on objects. The fact is that during operation, some objects can control others. For example, if an object has subobjects, then when the geometry changes, it can automatically rebuild the geometries of its descendants. In order for this to happen, a connection is established between the widgets - a “control” connection. Each object can have one or more subobjects "managed" by it.

There are three mechanisms for interaction between a program using Xt and the widget and X Window.

*Callback

Procedures ("procedures callback"). For any class, a set of actions is defined to which objects belonging to it must respond. For example, for any class a reaction to the destruction of a widget is provided. When an action is performed, either the standard Xt function or one or more procedures provided by the program are called. Such functions are called callback procedures or simply callback.

*Action

-procedures. The program can order a reaction to a particular complex event (group of events) coming from Xt. If an event occurs, Xt searches for and calls the appropriate function.

*Event handlers

- event handlers. This method is similar to the previous one, but faster and less flexible. It allows you to react only to simple (single) events, but not to their sequences.

General programming scheme

Programs running in X must perform a number of standard actions, such as: establishing a connection with the server, setting necessary properties for the window manager, and many other steps. If Xt is used, then all this is done with one procedure - XtInitialize(). It initializes the package itself, the resource manager (\term resource manager) X Window, and performs other necessary operations. A call to XtInitialize() (or XtAppInitialize()) must precede all other calls to Xt procedures. XtInitialize() returns the shell-widget identifier , which can be used as the root of the program object tree. Typically, the name of the program class is the same as the name of the program itself, only it begins with. capital letter. The resource manager uses the program's name and class to look up its parameters in the resource database.

Each program can set some parameters on the command line. Xt defines "standard" parameters that can be passed when running a program. In addition, the command line may contain non-standard parameters that are unique to this application. XtInitialize() scans the command line and places the corresponding data values ​​in the database.

During initialization, a program context is also created - a structure that stores all information about the application. The context is intended to protect the program from the influence of various modifications in the operating system. XtInitialize() creates some standard context (default context), but, nevertheless, starting from the fourth version of X, it is recommended to create a separate “personal” context for each individual instance of the program, for which, in terms of Xt, you should use a call to the XtAppInitialize() procedure ( instead of XtInitialize()). Note here that an application in Xt can have not one, as usual, but several objects " top level".

The next step after initialization is the stage of creating program control elements, describing the relationships between them, setting reactions to various events (registering event handlers and other similar objects). This can be done in different ways, but the traditional way is to use, for example, the XtCreateWidget() procedure to create an object, the XtManageChild() procedure to transfer control of an object to its parent, the XtAddEventHandler() procedure to register event handlers for widgets, etc. and so on.

After all program objects are prepared for work, their graphical representations (for example, windows corresponding to these widgets) are shown on the screen by the XtRealizeWidget() procedure.

The next stage is the main cycle - the cycle of receiving and sending events. It is implemented by calling the XtMainLoop() procedure (XtAppMainLoop()).

A program that uses only core X library (Xlib) procedures must itself consider each incoming event (receiving it from the event queue with an explicit call, such as XNextEvent() or XPeekEvent()) and respond accordingly. If a task has several windows, then before performing any actions, it is necessary to determine in which of the windows the event occurred and at what level of the hierarchy this event will be processed (will this object or its parent process this event?). All this is quite tedious.

Xt takes care of all the routine work. XtMainLoop() receives the next event and determines the window to which it is intended. There is a corresponding widget along the window. For the latter, an event handler, action procedure or callback are defined, registered to react to the event that has occurred. If there are any network, they are called. The mechanism described above is called event broadcasting.

XtMainLoop() (XtAppMainLoop()) automatically terminates the program when requested by the window manager.

Xt objects, their classification

Xt provides a set of tools for creating objects that programs use to communicate with the user and, in general, with the rest of the outside world.

Each widget created by the program is a representative of one class or another. Xt and packages based on it, such as OSF/Motif, Athena, Tk/tcl, Open Look, etc., have a large number of such classes. Creating new widgets that are not provided in standard libraries also requires creating (defining) the corresponding class, which is usually a time-consuming task.

Each class has a number of fixed characteristics that are common to all its instances (for example, a list of callback procedures). The values ​​of these characteristics may vary among the objects themselves.

All Xt classes form a hierarchy. If class B is closer to the top of the hierarchy than class D, then B is called the base class of D, and D is called the derived class (or subclass) of B.

Subclasses inherit the characteristics of all their base classes. This means that an instance of a class has the characteristics not only of its class, but also the attributes of all base classes.

In programs, each class is identified by a variable that points to the corresponding data structure. This variable is called a pointer to the class. The data in this structure is populated when Xt is initialized.

Main widget classes:

Object. An abstract class (a class that does not generate its own object) that is used as the root of a tree of all objects. It contains a single subclass:

Rectobj. An abstract class that is used to define some common characteristics necessary for the functioning of different types of objects (for example, for objects that do not have a window). It contains a subclass:

Core. The root of the tree of widget classes that have windows. This class defines characteristics that are common to all objects, such as the size of the widget and its position on the screen. Contains subclass:

Composite. Widgets belonging to this class can be parents of other objects. Instances of the Composite class define the following behavior for their subobjects:

* sets the location of “child” widgets according to certain restrictions;

* when destroyed, frees memory used by subobjects (when destroying a widget of the Composite class, all its “descendants” will be destroyed first);

* controls the appearance of the windows of its child widgets on the screen;

* controls the transfer of input focus between objects.

The Composite class contains subclasses:

Constraint. This class is a further extension of the base class. Its instances have additional capabilities to control the size and location of their descendants. For example, subobjects can be placed in a special order: in a row, in a column, etc.

Shell. This is a special class designed to interact with the window manager. widget from this class can have only one child. The Shell class contains subclasses:

OverrideShell. It is an important subclass of the Shell class. For a widget window of this class, the override_redirect attribute is set to True, i.e. the window manager does not control it. As a rule, windows of objects of this class do not have accessories added by the window manager (title, frame, standard buttons), and are used mainly to create menus of various types.

WMShel. This is a special subclass of the Shell class that contains additional fields needed to interact with the window manager. Contains:

VendorShell. This class is intended to provide the ability to interact with special window managers. This class contains subclasses:

TopLevelShell. Widgets of this class are usually used as shell objects of the program object tree. He contains:

ApplicationShell. A program can usually have only one instance, belonging to the ApplicationShell class.

TransientShell. This class differs from the previous one only in the features of interaction with the window manager. Widget windows of this class cannot be minimized (turned into an icon). But if the parent of a TransientShell class object is turned into an icon, then the widget window is removed from the screen. The TransientShell class is used to create dialogs.

Each of the widget classes, and therefore the objects created on its basis, have a fairly large number of parameters. In Xt terms these are called "resources". Xt provides a wide range of tools to work with them.

Additional Xt Features

Xt provides a mechanism for working with files (and external devices in general) in asynchronous mode. An application can register a procedure that will be called when data is ready or when read/write errors occur.

Xt gives an application the ability to perform certain actions at specified intervals. For example, periodically display the current time on the screen in a given window, etc. For such purposes, a special Xt mechanism is used - a timer. It provides a call at a specified time interval to a special function specified by the program.

Xt provides the ability to perform some action when the event queue is empty. This is accomplished by registering a special "work" procedure that Xt will call if the event queue is empty. Such functions are usually used to perform various actions and calculations in a very short time.

Each application, if necessary, can modify the usual cycle of receiving and distributing (processing) events - Xt provides a whole set of procedures for working with the event queue.

Xt has a mechanism called accelerators, which allows you to introduce event and action dependencies. Accelerators are similar to action procedures with the difference that an event (or group of events) occurring in one widget initiates a call to the corresponding action procedure for another object.

Xt supports several ways to work with widgets. Thus, the program, using the procedures provided by Xt, can show a window, set one or another operating mode for it, and close the window when it becomes unnecessary. These procedures are mainly used to create pop-up menus and dialogs. As a rule, all widget sets (for example, OSF/Motif) have their own much more convenient procedures for creating menus and dialogs.

Add-ons to Xt Xt is currently highly standardized by the X consortium, but there are no higher-level standards. Popular:

*OSF/Motif Toolkit;

* Athena Widget Set;

* OPEN LOOK Intrinsic Toolkit;

* InterViews;

* Tk/tcl.

The most common and almost de facto standard should probably be considered OSF/Motif.

Athena

The Athena Widget Set is provided by the X Consortium as part of the standard distribution of X. Athena was created through work on core applications and utilities during the Athena Project at MIT, which resulted in the X Window System.

Athena initially had “flat” graphics - all buttons, menus and other interface elements did not have shadows, i.e. were flat. About a year ago, AW3d was released - a variant of Athena Widgets, in which this drawback was eliminated.

Motif

Open Software Foundation Motif (OSF/Motif) is a package that includes a window manager, a set of utilities for performing various auxiliary operations, and a library of objects built on the basis of Toolkit Intrinsics.

Motif supports all Xt classes and therefore the resources of those classes, but to record the name and class of an object's resource, constants are used, starting with the prefix XmN and XmC, respectively. To record the type of resource, constants with the prefix XmR are used (instead of XtR, adopted in Xt).

Motif extends the many object classes provided by Xt. In particular, Motif supports a fairly large set of classes that allow you to create menus, scrollbars), clickable buttons, editing elements, etc.

In addition, Motif provides a special class of objects called gadgets - these form a separate class in Motif, XmGadget, which is a subclass of the RectObj class. They can also be used to create interface elements, but have the peculiarity that they do not have their own windows. To draw, a gadget uses its parent's window.

Each widget class has a fairly wide selection of both inherited and additional resources specific to it. They allow you to control such important characteristics of objects as background color, location on the screen, font of displayed text, etc.

Some of the Motif classes are not used to create widget instances (such classes are called abstract classes in object-oriented programming terminology). They contain the most common attributes and methods necessary for the functioning of various types of widgets.

Motif has two main subclasses of objects: XmPrimitive and XmManager (the XmGadget class was mentioned earlier). Both of these classes are abstract. The first of them inherits from the Core class and is used as a base for object classes that do not own other objects. Examples are clickable buttons, lists, etc. The XmManager class inherits from class Constraint and is used to create objects that can have and manage child objects.

Classification of objects

XmGadget class. When instances of regular Motif object classes (widgets) are created, a corresponding window is spawned. If a program uses a lot of widgets, this leads to a significant slowdown in the application. Time is spent both on creating windows and on further work with them. But it is easy to see that having a separate window for each object is not at all necessary. Labels, buttons, and many other widgets could be successfully used to draw windows of their parent objects. There is no window - no need to contact the server again, productivity increases and additional memory is not wasted.

Carrying out exactly this idea, Motif developers duplicated some object classes, creating two versions - with a window and without a window. Versions of objects that do not have windows derive their hierarchy from an abstract class - XmGadget, and they have the same general name. This special class of objects inherits its characteristics from the RectObj class, which, in turn, is an abstract class that contains the basic mechanisms for controlling the geometry of objects.

In addition to the fact that gadgets do not have their own windows, other restrictions are imposed on them. Thus, event handlers and translation tables cannot be defined for them. In addition, gadgets cannot have descendant objects. Otherwise, the functionality of the gadget and the corresponding widget is the same, so we will not describe them separately, we will only list them.

The XmGadget class contains subclasses:

* XmArrowButtonGadget.

* XmLabelGadget.\hfil

* XmPushButtonGadget.

* XmToggleButtonGadget.

* XmCascadeButtonGadget.

* XmSeparatorGadget.

XmPrimitive class. This abstract class contains:

XmArrowButton. An instance of the class is a button with a directional arrow drawn on it. The button can be clicked using the mouse or keyboard. The border of the control element can have a shadow, it is used to display the different states in which the object can be: free ("released") and pressed.

XmLabel. Representatives of this class (labels) are one of the simplest Motif objects. Labels are designed to display information: text or pictures (bitmaps).

XmPushButton. Representatives of this class are rectangular clickable buttons in which a line of text can be drawn.

If an object is selected, for example, by pressing the left mouse button while the cursor is on the object, then the color of the widget's border changes, which creates the effect of clicking. After releasing the button, the border color is restored. You can also click on such a widget from the keyboard - to do this, you need to give the object the input focus and press the spacebar (usually).

XmDrawnButton. Objects of this class are similar to clickable buttons with the only difference that not text is drawn in them, but an arbitrary image (pixel map).

XmToggleButton. Objects of this class are a small button, next to which, as a rule, there is explanatory text. A button can be in two states: on and off (i.e. it is a switch). They are marked by a change in the appearance of the control element.

A representative of this class is used to create so-called “check buttons”, which would be wiser to call “checkmarks”, and “radio buttons” - multi-position switches. The first ones are used to set logical parameters, i.e. having two meanings. The latter serve a similar purpose, but the set of values ​​in this case is finite and contains more than two elements. In this case, the form of the graphical representation of an object of the XmToggleButton type depends on whether it is used as a “check mark” or a “radio” button.

As a rule, widgets of the XmToggleButton class are combined into structures called, respectively, a check box and a radio box. These blocks, in turn, represent modifications of objects of the XmRowColumn class described below.

XmCascadeButton. Objects of this class represent clickable buttons and are used when creating menus. When you click on an object, a submenu of the next level appears.

XmList. Representatives of this class are some of the most interesting Motif objects. They are designed to display a list of strings and give the user the opportunity to perform various actions with the elements of the list. The user can select one or more rows represented in this object, and they are highlighted. In addition, if the list has input focus, then one of its elements is highlighted with a dotted frame. This frame is called the list cursor.

XmScrollBar. Objects of this class - scroll bars (scroll bars), as a rule, are used in conjunction with other objects, such as a list (XmList), text (XmText) and others. The scroll bar is designed to scroll an area if the information presented in it (list, text, picture, etc.) cannot be completely displayed in the window. Objects of the XmScrollBar class represent a strip (horizontal or vertical), along the edges of which there are arrow buttons. Clicking on any of them scrolls in the direction indicated by the arrow. On the scroll bar itself there is a slider (slider) - a rectangle highlighted in color. If you “hook” it with the mouse and “drag” it, this, as a rule, also leads to scrolling of the area.

XmSeparator. Objects of this class - separators - are used, as a rule, to improve the appearance of application windows. This widget is a vertical or horizontal strip (line) separating groups of objects. For example, separators can be used in menus to separate some commands from others, in dialogs - to isolate a group of pressed buttons from other elements, etc.

XmText. Objects of this class allow you to display one or more lines of text. If the lines do not fit in the window, then the image can be scrolled left-right and up-down. The text can be edited - the editing mode can be changed by the corresponding setting of object resources.

Motif provides a number of convenient procedures that allow you to perform a wide variety of operations with a widget of this class: obtain and modify data, copy a selected part of data to the system buffer (clipboard), and so on.

XmTextField. Objects of this class allow you to view and edit one line of text.

XmManager class. This class is abstract, i.e. not used to create objects. It defines the basic parameters needed to build widget classes that can manipulate other objects. These resources are needed to correctly display child widgets and control whether they receive input focus.

The XmManager class contains:

XmBulletinBoard. Objects of this class can have subobjects that are placed in the window in any way. The coordinates of child widget windows are measured in a coordinate system whose origin is in the upper left corner of the window of an object of the XmBulletinBoard class.

When you change the size of an object, for example, using the mouse, the initial location of the subobjects either does not change, or they are moved so as to avoid intersecting. If the widget window becomes smaller, parts of the subobjects may become invisible.

The XmBulletinBoard class contains:

XmForm. A distinctive feature of objects of this class (forms) is the ability to control the location of their subobjects by setting connections both between the form itself and the child widget, and between the subobjects themselves.

For each child widget, you can specify whether its left, right, bottom, or top edge is attached to. So, if the left and right edges of a subobject are snapped to the right edge of the form, then the distance from them to this edge will always remain the same. If the size of the form decreases, the subobject will move to the left, and if the size increases, then it will move to the right. You can bind one subobject to another. Then changing the position of the subobject to which the widget is bound will result in moving the bound object so that the distance between them is maintained.

When changing the size of the form, all connections between its subobjects are preserved.

XmSelectionBox. Objects of this class (“selection blocks”) represent an example of a composite widget and include a scrollable list where the user can select the element he needs, as well as a text field (XmTextField object) where the selected item in the list is displayed. The user can edit the selection made. The list and text field can have explanatory labels, specified using the corresponding widget of the XmLabel class. The XmSelectionBox class object also includes three pushable buttons (XmPushButton objects). By default, they are labeled "Ok", "Cancel" and "Help". And finally, there is one more element - a clickable button, called "Apply" by default. Initially, this subobject is created, but is not included in the list of managed widgets.

Using the selection block, the user can select the substring he needs in the list or enter it into the text field. The settings are confirmed by pressing the "Ok" button.

The XmSelectionBox class includes:

XmCommand. Objects of this class give the user the opportunity to select the desired command using a list of already entered commands, or by entering a command in a text field specifically provided for this in the widget.

XmFileSelection. Objects of this class allow you to view the current contents of different directories and select a particular file.

Objects of this class contain elements:

* 2 text fields: "Filter" and "Selection" (objects of the XmNextField class);

* 2 lists: "Directories" and "Files" (objects of the XmList class);

* 4 pushable buttons: "Ok", "Filter", "Cancel" and "Help" (objects of the XmPushButton class);

The "Filter" text field specifies a mask (template) for selecting from the entire set of files a certain subset that satisfies the condition specified in this field - matching the template - it is this subset that is shown in the "Files" list. The "Directories" list displays the subdirectories of the current directory. The "Selection" text field displays the file (its name) selected in the "Files" list, and in the same text field the user can enter and full name the file he needs manually. Four pressable buttons are used to perform various actions:

Ok - select the specified file;

Filter - updating the list of files displayed in the "Files" text field in accordance with the current mask;

Cancel - closes the widget window, no file selection occurs;

Help - a call for help.

XmMessageBox. Objects of this class are intended to provide the user with messages that arise during the operation of the program. This widget is composite. It has an area in which a line of text (message) and a special icon characterizing the type of message are displayed. In addition, the object has three clickable buttons. By default, they are labeled: "Ok", "Cancel" and "Help".

XmDrawingArea. Objects of this class provide the program with a window for drawing and displaying information. The class itself does not provide parameters that could be directly used to display graphics. But the lists of callback procedures available in this class allow you to receive notifications about the need to redraw the widget window and about receiving input focus.

XmFrame. Objects of this class are used to highlight some objects from others by surrounding them with a frame. The peculiarity of the widget class is that they can only have and manage one subobject.

XmPanedWindow. Objects of this class can combine heterogeneous widgets. The subobjects are separated from each other, and a special element called sash is placed between them. It looks like a small square and is used to resize child widgets. So, if an object of the XmPanedWindow class has two subobjects, then you can do the following: “hook” sash with the mouse and “drag” it in the desired direction (down-up or left-right) - while the longitudinal size (size along the direction in which it was "dragged" sash) one child object will increase "at the expense" of the other (the size of the other will decrease), the transverse dimensions of both subobjects will be preserved. The "lateral" size of an object of the XmPanedWindow class is determined by the maximum similar size of its subobjects.

XmRowColumn. Objects of this class can combine heterogeneous widgets. Subobjects are arranged in a certain order - in the form of a matrix. widget of the XmRowColumn class are the basis for creating the following objects:

check box - “block of checkable buttons” (i.e. objects of the XmToggleButton class or XmToggleButtonGadget class); Among the buttons available in the “block” several can be selected (“enabled”) at the same time;

radio box - “block of radio buttons” (i.e. XmToggleButton or XmToggleButtonGadget objects); Among the buttons available in the “block”, only one can be selected (“enabled”) at a time;

pulldown menu - "drop-down menu" - a submenu window that appears after selecting a button in the top-level menu (menu bar); menu items are arranged vertically;

option menu - button with an associated menu; when you click the button, a menu window appears from which one parameter value is selected; menu items are arranged vertically;

popup menu - a “pop-up menu”, which is usually called up by clicking the third mouse button; the menu window appears in the place where her cursor is located; menu items are arranged vertically;

menu bar - a top-level menu containing a number of buttons (objects of the XmCascadeButton or XmCascadeButtonGadget class), which are used to call various submenus (pulldown menu); Menu items are arranged horizontally.

XmScale. An object of this class is a rectangular area containing a fixing slider, using which the user can select the value of the parameter associated with the object from a specified range.

XmScrolledWindow. An object of this class provides the ability to display and view some information (text, picture, list). Such a widget, as a rule, contains a subobject in which the data intended for viewing is located (this can be an object of the XmText, XmDrawingArea, etc. class). For more convenient viewing of data, horizontal and vertical stripes scroll.

This class contains a subclass

XmMainWindow. Objects of this class represent a separate interface component, usually consisting of the following parts:

* top level menu,

* command window,

* "Workspace,

* message window,

* and two scroll bars (horizontal and vertical).

Subobjects can be separated by separators.

XmMenuShell and XmDialogShell classes. Motif provides an XmMenuShell object class for creating various menus. This class inherits from the OverrideShell class (from Xt).

As already mentioned when describing Xt, the TransientShell class is used to create program objects that, on the one hand, directly contact the window manager, and on the other hand, have features that distinguish them from ordinary top-level windows. The main one of these features is that the widget of the TransientShell class cannot be minimized. But they are removed from the screen if the parent turns into an icon. This kind of widget is usually used to create auxiliary program windows.

Motif uses the specified properties of the TransientShell class and extends them into the derived class XmDialogShell. The latter serves as the shell object of the dialog.

The structure of the dialog box in Motif can be represented as follows:

XmDialogShell class object

An XmManager subclass object, such as XmBulletinBoard or XmForm

Various control elements: buttons, text input fields, etc.

The library has a set of procedures that facilitate the creation of the described design.

Dialogues

As stated, the design of a dialog box in Motif is as follows: first there is an object of the XmDialogShell class, which then includes a widget of one of the subclasses of the XmManager class; this object is used to host various objects.

The library provides special procedures for creating dialogues. They differ in the widget type, which is a child of the XmDialogShell class object.

Text output

The library has a fairly large number of widgets that are used to display text information. These are XmLabel with subclasses, XmText, etc. To specify possible fonts that can be used when drawing lines, the XmNfontlist resource is used. It is of type XmFontlist. Its meaning is a set of “font”/”font tag” pairs.

Tags (labels) are intended to make programs independent of specific fonts specified by the user. This is done as follows: the application is created in such a way that all functions that work with lines of text contain not the fonts themselves, but their labels. When the task is compiled and started, the correspondence between tags and specific fonts is determined. The latter are used for drawing.

Motif has tools not only for working with strings of texts displayed in a single font, but also allows you to work with objects such as “composite strings” - i.e. lines of text that use many fonts. There is a set of tools for creating such strings, working with them and converting them to regular, "single-font" strings.

Working with Images

Motif itself works with images, presenting them in an internal format, which is a simple bitmap, which is specified using the XImage structure.

Control input focus

Motif supports two input focus models. The first of them is implicit (pointer): focus is given to the widget into which the mouse cursor moves. The second model is explicit: to transfer focus, you need to place the mouse cursor in the widget window and click on the left mouse button. When a widget or gadget receives input focus, its border is highlighted.

In addition to these models of passing and receiving input focus, there is also a mechanism for passing input focus from one widget to another. Objects can be combined into groups - this can be done by setting the required values ​​of the corresponding resources, or it can be left to the system. In the latter case, Motif automatically links the widget using built-in rules. So, for example, an object of the XmMessageBox class contains three groups: one is the “main” dialog object (XmForm class), the second is the “label” in which the message is presented to the user, the third is the pressable buttons.

Input focus is transferred both from one object (in a group) to another, and from group to group.

Transferring focus within a group is done using the arrow keys, and from group to group using the tab key (that's why the groups themselves are called Tab groups). When a group is given focus, the input focus in that group is given to the first object that can receive focus (an object can be prevented from receiving focus by setting the corresponding resource to an appropriate value). The order in which input focus is transferred within a group is the same as the order in which its widgets are created. In this case, usually the key combination moves the focus in the opposite direction.

Motif also provides a number of routines that can be used to control input focus.

Lesstif Quite recently, a freeware analogue of Motif was released, completely compatible with it. It's called Lesstif. It is freely available in its original form and compiled for various platforms on the Internet.

Tk/tcl

Tcl - read: - stands for: "tool command language" (instrumental command language). It consists of two parts: the language itself and the library.

The tcl language has a simple syntax and is easy to program in. In its original form, tcl is an interpreter. Allows you to create new constructs, like functions or programs, which provides the skilled programmer with a powerful tool for developing not only final applications, but also his own extension of the TCL language, creating and maintaining his own style.

The tcl library provides the ability to use TCL language interpreters in application programs, and therefore include scripts written in the TCL command language in programs. The library contains a lexical analyzer for the TCL language, functions that implement built-in TCL commands, and allows you to attach user subroutines (function calls) to TCL commands. This arrangement is possible for both C and C++.

Tk is a Motif-compatible toolkit for developing graphical user interfaces in the X Window environment. In addition to the standard interface to C and C++, it includes an interface to tcl, providing the ability to use Tk tools from within the tcl command interpreter environment. This means that in addition to standard programming in C and C++, the interface parts of the application can be implemented in the form of scripts in the TCL language and these interface parts (dialogs, screen layouts, etc.) can be edited dynamically, during the operation of the final program, using tcl commands

The wish window environment allows you to create applications with graphical user interfaces using only the TCL language.

Similar documents

    Programming systems and their graphic capabilities. Development of a multimedia course that promotes effective learning of the topic by basic school students Graphics capabilities programming language" (using the example of the Basic and Pascal programming languages).

    thesis, added 12/29/2010

    Screen graphic components, system objects and functions. A system of means for user interaction with a device. History of graphical user interfaces personal computers, their classification. X Window System.

    presentation, added 05/22/2012

    Programming and basic graphics capabilities. Basic structures for the view and two constructors with arguments. Further coordinates of the point and initialization of a new one. Storing and changing the coordinates of the upper left corner of the rectangle.

    laboratory work, added 12/01/2011

    Vector computer graphics. Graphic primitives. Graphical language capabilities Pascal programming. Guidelines to learning graphics in the Pascal programming language. Plotting function graphs.

    course work, added 06/13/2007

    Development of a program for the Windows operating system using VisualC++ (6.0, .NET). Covering the Basics software modeling operation of the appliance (electric kettle). Rules for creating device classes and its graphical interface.

    course work, added 06/03/2014

    Computer graphics. Presentation of graphic information on a computer. Graphic formats. Graphic editor. Vector graphics. CorelDraw. Characteristics of the program and interface. Technological capabilities and use of the CorelDraw program.

    course work, added 05/19/2007

    The role of distributed computing systems in solving modern problems. DVM tool system for developing parallel programs. Tools for constructing a formal graphical interface model. Requirements for the graphical interface of the DVM system.

    course work, added 10/15/2010

    The essence of programming using Delphi environments 7 and its basic graphics capabilities. The structure of an offline compiled software module and its principles. Basic techniques for working with graphic procedures, constructing an arc, circle and ellipse.

    course work, added 12/16/2011

    Areas of application computer graphics. Kinds computer graphics. Color resolution and color models. Software for creating, viewing and processing graphic information. Graphics capabilities word processors, graphic editor.

    test, added 06/07/2010

    The evolution of graphical user interfaces. The X Window System and Window Managers. Description of the KDE and GNOME desktop and application. An overview of the basic principles of interface organization in the Windows system, a description of its application software package.

Contributed by Saleem Gul and Tomas Pavek

This tutorial covers creating a simple graphical user interface and adding simple server-side functionality to it. In particular, we'll look at the code that defines the behavior of buttons and fields on a Swing form.

We'll look at the layout and structure of the GUI, then add some buttons and text fields. Text fields are designed to receive user-entered information and display the result of the program. The button will initiate the operation of functions built into the client part of the program. The application being created is a simple but fully functional calculator.

For a more detailed guide to the GUI Designer development features, including video demonstrations of various development features, see .

Estimated duration: 20 minutes

Exercise 1: Creating a Project

The first step is to create an IDE project for the application you are developing. Let's name the project NumberAddition.

  1. Choose File > New Project. You can also click the New Project icon on the IDE toolbar.
  2. In the Categories area, select the Java node. In the "Projects" area, select "Java Application". Click "Next".
  3. Enter NumberAddition in the Project Name field and specify a path, such as your home directory, as the project location.
  4. Check the "Use separate folder to store libraries" and specify the location of the libraries folder (optional). For more information, see Share a library with others in a document Developing Applications with NetBeans IDE.
  5. Remove the "Create Main Class" checkbox if it is checked.
  6. Click the "Done" button.

Exercise 2: Creating the Front End

To continue the interface creation process, you need to create a Java container in which the other required GUI elements will be placed. In this activity, a container will be created using a JFrame element. The container will be placed in new package, which will appear in the "Source Packages" node.

Creating a JFrame Container

  1. In the Projects window, right-click the NumberAddition node and select New > Other.
  2. In the file creation dialog, select a category Swing GUI Forms and the JFrame Form file type. Click "Next".
  3. Enter NumberAdditionUI as the class name.
  4. Select the my.numberaddition package.
  5. Click the "Done" button.

The IDE creates the NumberAdditionUI form and the NumberAdditionUI class in the NumberAddition application and opens the NumberAdditionUI form in the GUI Builder. The my.NumberAddition package replaces the default package.

Adding Elements: Creating a Front End

Next, using the "Palette" window, the external interface of the application is filled with the JPanel. After this, three JLabel elements (text labels), three JTextField elements (text fields), and three JButton elements (buttons) are added. If you have not previously worked with the GUI designer, see Designing a Swing GUI in the NetBeans IDE for information about component placement.

After dragging and placing the above elements, the JFrame element should look like the image below.

If there is no Palette window in the upper right corner of the IDE, choose Window > Palette.

  1. To begin, select a panel from the Swing Containers category in the palette and drag it onto the JFrame.
  2. The JPanel will be highlighted. Go to the Properties window and click the ellipses button (...) next to the Border field to select a border style.
  3. In the Border dialog box, select TitledBorder from the list and enter Number Addition in the Title field. Click "OK" to save your changes and close the dialog box.
  4. The screen should now display an empty "JFrame" element with the title "Number Addition" as shown in the image. According to the picture, add three JLabels to it, three text fields JTextField and three JButtons.

Renaming elements

This step will rename the elements that have been added to the JFrame element.

  1. Double-click jLabel1 and change ntrcn ("text" property) to First Number.
  2. Double click jLabel2 and change the text to Second Number.
  3. Double click jLabel3 and change the text to Result.
  4. Remove the default text from jTextField1. The displayed text can be converted to editable text. To do this, right-click the text field and select "Edit Text" from the pop-up menu. This may require you to restore jTextField1 to its original size. Repeat this step for the jTextField2 and jTextField3 fields.
  5. Change the display text of jButton1 to Clear . (To change the text of a button, right-click the button and select Edit Text. Alternatively, you can click the button, pause, and click again.)
  6. Change the display text of jButton2 to Add .
  7. Change the display text of jButton3 to Exit .

Now the finished GUI should look like the image below:

Exercise 3: Adding functionality

This exercise will add the required functionality to the Add, Clear, and Exit buttons. The fields jTextField1 and jTextField2 will be used for user input, and jTextField3 will be used to display the result of the program. Created program is a simple calculator. So let's get started!

Adding functionality to the Exit button

In order for the buttons to become functional, each of them must be assigned an event handler, which will be responsible for responding to events. In our case, we need to identify the button click event - either by clicking the mouse or using the keyboard. Therefore, the "ActionListener" interface will be used to handle "ActionEvent" events.

  1. Right-click the "Exit" button. From the pop-up menu, select Events > Action > actionPerformed. Please note that the menu contains many other events that the program can respond to! When you select the actionPerformed event, the IDE will automatically add an ActionListener to the Exit button and create a handler method to handle the actionPerformed listener method.
  2. The IDE automatically opens the Source Code window, showing you where to insert the action you want the button to perform when you click it (with your mouse or keyboard). The "Source Code" window should contain following lines: private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) ( //TODO add your handling code here: )
  3. Now let's add the code for the action that the "Exit" button should perform. Replace the TODO line with System.exit(0); . The finished code for the "Exit" button should look like this: private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) ( System.exit(0); )

Adding functionality to the "Clear" button

  1. Right-click the "Clear" button (jButton1). From the menu that appears, select "Events > Action > actionPerformed".
  2. Clicking the "Clear" button should result in all text being removed from all "jTextField" text fields. To do this, add code similar to the one above. The finished source code should look like this: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)( jTextField1.setText(""); jTextField2.setText(""); jTextField3.setText(""); )

This code removes text from all three JTextFields, leaving them empty.

Adding functionality to the "Add" button

The "Add" button should do three things.

  1. It first takes the user's input in the jTextField1 and jTextField2 fields and converts them from a "String" type to a "Float" type.
  2. It will then perform the addition of the two numbers.
  3. Finally, it will convert the sum to a String and place it in jTextField3 .
Let's begin!
  1. Click the Design tab at the top of the workspace to return to the Form Design screen.
  2. Right-click the "Add" button (jButton2). From the pop-up menu, select Events > Action > actionPerformed.
  3. Add code for the actions that the "Add" button should perform. The finished source code should look like this: private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)( // First we define float variables. float num1, num2, result; // We have to parse the text to a type float. num1 = Float.parseFloat(jTextField1.getText()); num2 = Float.parseFloat(jTextField2.getText()); // Now we can perform the addition = num1+num2; result to jTextField3. // At the same time, we are going to // change the value of result from a float to a string. jTextField3.setText(String.valueOf(result));

Now the program is completely ready, and you can start assembling and executing it.

Exercise 4: Executing the Program

To run the program in the IDE, follow these steps:

  1. Select Run > Run Main Project (alternatively, press F6).

    Note. If you open a window indicating that Project NumberAddition does not have a main class specified, you should select my.NumberAddition.NumberAdditionUI as the main class in the same window and click OK.

To run the program outside the IDE, follow these steps:

After a few seconds the application will launch.

Note. If double-clicking a JAR file does not launch the application, learn more about setting up associations JAR files For the operating system you are using, see

You can also run the application from the command line.

To run the application from the command line, follow these steps:

  1. Open a command prompt or terminal window.
  2. At the command prompt, change the current directory to the NumberAddition/dist directory.
  3. At the command prompt, enter the following statement: java -jar NumberAddition.jar

    Note. Make sure that my.NumberAddition.NumberAdditionUI is set as the main class before running the application. To check this, right-click the NumberAddition project node in the Projects panel, choose Properties from the pop-up menu, and select the Run category in the Project Properties dialog box. The Main Class field should show my.numberaddition.NumberAdditionUI .

Event Processing Engine

This tutorial looked at responding to a simple button click event. There are many events that an application can respond to. In the IDE, you can view the list of available events that can be processed by GUI elements as follows:

  1. Return to the NumberAdditionUI.java file in the editor. Click the "Design" tab to view the GUI structure in GUI Builder.
  2. Right-click any GUI element and select "Events" from the menu that appears. Now you can simply explore the contents of the menu without selecting any items.
  3. Alternatively, you can select "Properties" from the "Window" menu. In the Properties window, click the Events tab. The "Events" tab allows you to view and change event handlers associated with the current active element graphical interface.
  4. The application can also respond to key presses, single, double, or triple clicks, mouse pointer movements, window resizing, and input focus movements. The "Events" menu allows you to automatically create event handlers for all these events. The most common of these is the "Action" event. (For more information, see how to handle events in the Sun Java Events Tutorial.)

How are events processed? Whenever you select an event from the event menu, the IDE automatically creates what is called an event listener and associates it with the developer component. To learn more about event processing, follow these steps:

  1. Return to the NumberAdditionUI.java file in the editor. Click the "Source" tab to view the GUI source code.
  2. Scroll down to see the implemented jButton1ActionPerformed() , jButton2ActionPerformed() , and jButton3ActionPerformed() methods. These methods are called event handlers.
  3. Now go to the initComponents() method. If this method is missing, find the Generated Code line and click the + sign next to that line to display the hidden initComponents() method.
  4. Notice the blue block surrounding the initComponents() method. This code was automatically generated by the IDE and cannot be modified by the user.
  5. Now look at the initComponents() method itself. Among other things, it contains code that initializes GUI elements and places them on the form. This code is generated and updated automatically as you place and change elements in design mode.
  6. In the initComponents() method, find the following snippet: jButton3.setText("Exit"); jButton3.addActionListener(new java.awt.event.ActionListener() ( public void actionPerformed(java.awt.event.ActionEvent evt) ( jButton3ActionPerformed(evt); ) ));

    At this point, an "ActionListener" event listener object is added to the GUI element, in this case jButton3 . The "ActionListener" interface has an "actionPerformed" method on the "ActionEvent" object, which is implemented by simply calling the jButton3ActionPerformed event handler. This button now responds to action events. Each time the button is clicked, an "ActionEvent" is generated and passed to the "actionPerformed" method of the event listener interface, which executes the code the developer provided for that event in the event handler.

  7. Java GUI Applications Learning Card

July 09, 2003

With the advent of various visual application development tools, writing graphical interfaces for programs has turned into something like a child's game. I poked it with the mouse and a form appeared; I poked it a second time and a button appeared. It seems to me that many people now do not think about another way of programming in graphical environment. Of course, you can’t argue against progress; when writing large projects, all these conveniences come in very handy. But that's not what this conversation is about. Sometimes it comes to the point of absurdity: a primitive application is written using MFC, VCL, etc. Such programs devour memory like termites and, with their fat bodies, occupy extra disk space. As a rule, MFC/VCL analogues “weigh” ten to twenty times more than programs written on a pure API. A Visual Basic(may God forgive me for this phrase) with its msvbvmXX.dll? And much more system resources are consumed (several times). Poor users, denying themselves beer, save money to buy new hardware. Isn't it a pity for the poor things? Not only programmers drink beer? There is another positive aspect of API coding: the programmer becomes closer to the operating system. Accordingly, he understands and controls it better. And it’s simple - it’s a very exciting activity. I repeat, all of the above applies specifically to small, simple programs; in large projects everything is completely different.

I hope I convinced you. Go.

We will look at creating a simple window interface with minimal functionality. This will be a simple window with two input fields and two buttons. When you click on the "Copy" button, the text from the first input field will be copied to the second. When you click on the "Close" button, the program will complete its work. In the future, it can serve as a template for writing other, more complex applications. We will communicate in C/C++, although we will not offend Delphi either. General principle the same, only the syntax is different. To work with system messages and API functions, you need to include header files in your project; in C/C++ this is windows.h, in Delphi these are the windows and messages modules.

Any program in Windows OS consists of three main parts: the main function, the message loop and the window function, which processes all messages sent to the window.

Our program starts executing with the WinMain() function. This is the main function. The WinMain() function typically performs the following tasks:

  • Defines the window class. Not to be confused with an OOP class.
  • Registers this class in the system.
  • Creates the main application window and other controls.
  • Displays a window on the screen.
  • Starts the message processing loop.
  • It is declared this way: int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) Let's look at the parameters:
    • hInstance is a handle to the current application instance.
    • hPrevInstance is a handle to the previous instance of the application, if it is running.
    • lpCmdLine - pointer to a line containing parameters passed to the program at startup.
    • nCmdShow - a constant that determines how the window is displayed. (See SW_ constants).

In Delphi we will not see such a picture; in this development environment the main function is hidden from the programmer by the compiler. Although, of course, it is present in the final code. To register a window class, you need to fill in the fields of the structure of type WNDCLASS (in Delphi TWNDCLASS). For this purpose, we have declared the wcl variable.

wcl.hInstance = hInstance; A handle to the current application instance, the hInstance variable is initialized by the WinMain() function. In Delphi it is initialized implicitly.

wcl.lpszClassName = szWinName; Class name. We created and initialized the string variable szWinName in advance.

wcl.lpfnWndProc = WindowFunc; A pointer to a window function. wcl.style = 0; A constant that specifies the window style. The CS_ flags are used for this, I just cleared them to zero. You can specify a combination of flags using the bitwise "or" operation. wcl.hIcon = LoadIcon(NULL, IDI_ASTERISK); A handle to the application icon, as returned by the LoadIcon() function. I uploaded a standard icon. See IDI_ constants.
  • wcl.hCursor = LoadCursor(NULL,IDC_ARROW); A handle to the application cursor, as returned by LoadCursor(). I loaded the standard arrow. See IDC_ constants.
  • wcl.lpszMenuName = NULL; Pointer to a string specifying the name of the menu resource for this window class. No menu, no sign.
  • wcl.cbClsExtra = 0; Reserved field. Let's reset.
  • wcl.cbWndExtra = 0; Reserved field. Let's reset.
  • wcl.hbrBackground = (HBRUSH)COLOR_WINDOW; Window color. The COLOR_WINDOW constant is cast to type HBRUSH (in Delphi there is no need to cast). Also, using the GetStockObject() function, you can set the window brush color or background image. Now, feel free to register the window class.
  • The eighth parameter is the owner window. At the main window, the owner is the desktop (0). The controls have a main window.
  • The ninth is a pointer to the menu handle. No menu, no sign.
  • The tenth parameter is a handle to the current application instance.
  • Eleventh - Used when creating applications with an MDI interface. We do not need.
The function returns a handle to the created window, which is stored in the hMainWnd variable.
A window handle is a unique number in the system that identifies a window or control.

Next we will create the necessary controls. All controls are the same windows, they just have a different class name. There is no need to register control classes; they are already predefined in the system. Button - button class. Input field - class edit. Caption - class ststic. There are many classes that correspond to standard controls. We create controls using the familiar CreateWindow() function and the unfamiliar CreateWindowEx() function. CreateWindowEx() allows you to create a window with an advanced style. We use it to create input fields. This function has added the first parameter, which sets this most advanced style, the remaining parameters are the same as CreateWindow(). Controls are child windows, their owner is the main window.

When creating controls, in the function parameters you must specify the main window descriptor, as well as the window style WS_CHILD. Appearance and the functionality of the controls can be manipulated using the flags: WS_, ES_, BS_, SS_, combining them with the bitwise “or” operation. When creating controls, we initialize the corresponding variables with their descriptors, which are returned by the CreateWindow() and CreateWindowEx() functions. We will need these descriptors to further work with controls. We display the window we created on the screen and redraw it.

The GetMessage function selects the next message from the application's message queue and sends it to the window.
  • The first parameter is a structure of type MSG (in Delphi of type TMSG)
  • The second parameter is a handle to the window to which the message is intended. If NULL or 0, then all application windows.
  • The third and fourth - allow you to set the range of received messages. If 0, then all messages addressed to the window.
GetMessage - returns FALSE when a WM_QUIT message appears, in which case the loop is exited and the application exits. TranslateMessage - translates keys into keyboard messages.

DispatchMessage - sends a message to the window function for processing. The window function provides program functionality by processing system messages . The window function is a CALLBACK function, i.e. called operating system

in response to a new message received. The window function is declared like this:

  • LRESULT CALLBACK WindowFunc(HWND hMainWnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
  • HMainWnd - handle to the main window.
  • iMsg - message number. See WM_ constants.

lParam and wParam are message parameters.

When a message appears, we can compare the iMsg parameter with one of the WM_ constants and program the program to react accordingly.

For example: When the left mouse button is pressed while the mouse pointer is over the client area of ​​the window, the WM_LBUTTONDOWN event is raised. The window function is called, the value of the WM_LBUTTONDOWN constant is entered into the iMsg parameter, we can check the condition and program the program reaction we need.

Inside the window function is a selection statement that performs the task described above. The selection operator must have a default handler, which is implemented by the function DefWindowProc(hMainWnd, iMsg, wParam, lParam); If this is not done, our program will die without reviving. Many messages are processed by the system itself, such as: resizing a window, minimizing/maximizing a window, calling system menu

etc. This is what DefWindowProc() is for.

When working with window controls, a WM_COMMAND message is sent to the window owner, with lParam containing the handle to the control, and the high byte of the wParam parameter is the identifier of the event raised on the control. For example: when you click on a button - BN_CLICKED. See constants BN_, WM_. We can close the program using the PostQuitMessage(0) function. This function sends a WM_QUIT message to the window.

  • A few words about how to write such programs in Delphi. Create a new project, launch Project Manager, delete Unit1 along with the form. Press Ctrl + F12 and open the project file. We remove the forms module from the uses, add windows and messages there. We delete everything between begin and end. The workpiece is ready. You can code. It is impossible to write programs using a pure API without help, which should always be at hand. If you were Gates himself, you wouldn’t remember everything. I recommend:
  • first of all - MSDN; reference system
  • There is Russian help on the Win32 API on the website http://www.soobcha.ru/rushelp.
That's all.
Good luck.

Bobachenko Maxim Download: CreateWnd.zip(2.6K)
the archive contains the files windows.cpp and windows.dpr