Delphi's ninth lesson Windows programming

Source: Internet
Author: User

Delphi uses the Object Pascal and Visual Control Library (VCL) to encapsulate the underlying Windows APIs perfectly, so there is little need to use the underlying Pascal language to build Windows applications or call Windows API functions directly. However, if there is a special situation, VCL does not support, Delphi programmers have to directly face the Windows programming. However, only in extremely special cases, such as the development of Delphi new controls based on unusual API calls, do you need to do this, and here I don't want to discuss this, I just want to show you a few Delphi elements interacting with the operating system and the Windows programming techniques that Delphi programmers can benefit from.

Windows handle

Delphi introduces a number of data types from Windows, where the handle is the most important. This type of data is named Thandle, which is defined in a Windows cell:

type  Thandle = Longword;

Handle data types are implemented numerically, but are not used as numbers. In Windows, a handle is a reference to a system's internal data structure. For example, when you operate a window, or a Delphi form, the system will give you a handle to the window, the system will notify you: you are operating window 142th, in this case, your application will be able to request the system to operate on window 142th-moving the window, changing the window size, to minimize the window to the icon, Wait a minute. In fact, many Windows API functions take a handle as its first parameter, such as GDI (graphics device Interface) handle, menu handle, instance handle, bitmap handle, and so on, not just the window function.

In other words, a handle is an internal code that can refer to special elements that are controlled by the system, such as windows, bitmaps, icons, memory blocks, cursors, fonts, menus, and so on. It is seldom necessary to use the handle directly in Delphi because the handle is hidden inside the form, Bitmap, and other Delphi objects. Handles are useful when you want to invoke Windows API functions that are not supported by Delphi.

Now for a simple example of Windows handle, refine this section. Example whandle the form of a program is simple and has only one button. As defined in the main form text below, I added the OnCreate event for the form and the OnClick event for the button in the code:

Object Formwhandle:tformwhandle  ' Window Handle '  OnCreate = formcreate  Btncallapi:tbutton    ' Call API '    OnClick = Btncallapiclick  endend

When the form is created, the program obtains the window handle for the form through the handle property of the form itself. Call IntToStr, convert the handle value to a string, and then add it to the form header, 9.1:

procedure Tformwhandle.formcreate (Sender:tobject); begin  " + inttostr (Handle); End;

Because Formcreate is a method of a form class, it can directly access other properties and methods of the same kind. Therefore, in this process we have direct access to the Caption property and the handle property of the form.

Figure 9.1: Example Whandle shows the form handle, each time the program runs the resulting handle value is different

If you execute this program more often, you will usually get different handle values. This value is actually determined by the Windows operating system and returned to the application. (The handle is never determined by the program, and the handle does not have a predefined value, the handle is determined by the system, and each time the program executes, a new value is generated.) )

When you click the button, the program will call the Windows API function SetWindowText, which will change the caption of the window based on the first pass parameter. To be more precise, the first parameter of the API function that is used is the handle of the form that needs to be modified:

Tformwhandle.btncallapiclick (Sender:tobject); begin  ' Hi '); End;

This code is equivalent to the previous event handler, which changes the form's caption by assigning a new value to the Caption property of the form. In this case, it makes no sense to call an API function because it is easier to do with Delphi. However, some APIs do not have the corresponding function in Delphi, you need to call the API directly, which you will see in the advanced example later.

External declarations

Another important element involved in Windows programming is the external declaration. External declarations were originally used to connect the external functions written in the Pascal code to assembly language, and are now externally declared for Windows programming to invoke dynamic Connection library DLL functions. There are many such declarations in Delphi's Windows unit:

Forward declarationstdcall; //External declaration (instead of actual code) function External ' Gdi32.dll ' name ' LineTo ';

This statement indicates that the code for the function LineTo is saved in the GDI32.DLL Dynamic link library (one of the most important Windows system libraries). When actually applied, the function name in the outer declaration can be different from the function name in the DLL.

Generally you do not need to write the declaration as you have just mentioned, because these declarations are already included in the Windows Unit and some Delphi system units. You only need to write external declarations when you call a custom DLL or call a Windows function that is not defined in Delphi.

Note: in 16-bit Delphi, the external declaration uses the library name without the extension, followed by the name Directive (shown above) or an index instruction followed by the ordinal of the function in the DLL. Although Win32 still allows the DLL function to be accessed by ordinal, Microsoft has declared that it will not be supported in the future, a change that reflects how the system library is accessed. Also note: The current Delphi Windows unit has replaced the 16-bit Delphi Winprocs and wintypes units.

callback function

The objet Pascal support process type has been learned from the sixth chapter. Procedure types are commonly used to pass callback functions to Windows API functions.

First, what is a callback function? A callback function is an API function that performs a given operation on a set of internal elements of a system, such as a function that can manipulate all of the same windows. This function is also called an enumeration function, which is a function that is passed as a parameter, representing the operation performed on all internal elements, and the type of the function or procedure must be compatible with the given procedure type. The application of Windows callback functions is more than one of the above, but only the above simple applications are studied here.

Now consider the EnumWindows API function, which is prototyped as follows (from the Win32 Help file copy):

BOOL EnumWindows (  wndenumproc lpenumfunc,  //Address of callback function  // application-defined value  );

Of course, this is a C language definition. We can look at the Windows unit and find the corresponding Pascal language definition:

function EnumWindows (  lpenumfunc:tfnwndenumproc;  stdcall;

Looking at the Help file, we find that the function passed as a parameter should belong to the following type (also in C):

BOOL CALLBACK Enumwindowsproc (  //Handle of parent window  //application-defined value  ) ;

This is consistent with the following Delphi process type definition:

type  function (Hwnd:thandle;    stdcall;

The first parameter is the handle to each main form, and the second parameter is the value passed when the EnumWindows function is called. In fact, there is no corresponding Tfnwndenumproc type definition in Pascal, it is just a pointer. This means that we need to pass a function with the appropriate parameters and use it as a pointer, that is, take the address of the function instead of calling it. Unfortunately, this also means that the compiler does not give a hint if an error occurs with a parameter type.

Whenever you call a Windows API function or pass a callback function to the system, Windows requires the programmer to follow the stdcall call contract. By default, Delphi uses another more efficient invocation contract with the keyword register.

The following is a definition-compatible callback function that reads the title of the window into a string and then adds it to a list box for a given form:

function stdcall; var  text:string; begin  SetLength (Text, +);  GetWindowText (Hwnd, PChar (Text), +);  FORMCALLBACK.LISTBOX1.ITEMS.ADD (    ': ' + Text);  Result: = True; End;

A form has a list box that almost covers the entire form, with a small panel at the top of the form and a button on the panel. When the button is pressed, the EnumWindows API function is called, and the GetTitle function is passed to it as a parameter:

procedure Tformcallback.btntitlesclick (Sender:tobject); var  Ewproc:enumwindowsproc; begin  ListBox1.Items.Clear;  Ewproc: = GetTitle;  EnumWindows (@EWProc, 0); End;

You can call the GetTitle function directly without first saving the value to the procedure type temporary variable, which is done to make the callback process clearer. The results of the program run are really interesting, as you can see in Figure 9.2, and the results show all the main windows that are running in the system, most of which are hidden, which you don't normally see, many of which actually don't have a title.

Figure 9.2: Example callback output--all current main forms, including visible and hidden forms

The smallest Windows program

To fully introduce the Windows programming and Pascal language, now I present a simple but complete application that was built without the use of the VCL library. This program simply takes command-line arguments (stored in the system's full variable cmdline) and extracts the information from the parameters using the two Pascal functions of ParamCount and PARAMSTR. Where the first function returns the number of arguments, the second returns the arguments for the given position.

Although users rarely manipulate command-line parameters in a graphical user interface environment, Windows command-line parameters are important to the system itself. For example, once you have defined the file name extension and the application's association, simply double-click the associated file to execute the program. In fact, when you double-click a file, Windows launches the Affiliate program and passes the selected file to it as a command-line argument.

The following is the complete source code for the project file (a DPR file, not a pas file):

 Program Strparam; uses  Windows; begin  //Show the full string  MessageBox (0, CmdLine,     ' strparam Command line ', MB_OK);  //Show the first parameter  if  then    MessageBox (0, PChar (paramstr (1)),       ' 1st strparam Parameter ', MB_OK)  else    MessageBox (0, PChar (' No parameters '),       ' 1st strparam Parameter ', MB_OK);  End.

The output code uses the MessageBox API function, which makes it easy to avoid the VCL library. In fact, like the pure Windows program above, the advantage is that the memory is small, program execution file about 16k bytes.

In order to give the program command line arguments, you can use the Delphi Run > Parameters menu command. Another option is to open Windows Explorer, locate the directory that contains the program execution files, and then drag the file you want to execute onto the executable file, and Windows Explorer will use the drag-and-drop filename as a command-line argument to begin executing the program. Figure 9.3 shows the resource manager and the corresponding output.

Figure 9.3: Drag and drop a file onto the execution file, providing command-line arguments for example Strparam

Conclusion

In this chapter, we introduce the underlying content of Windows programming, and discuss handles and simple Windows programs. For regular Windows programming tasks, you typically only need to use the visual development tools provided by Delphi and the VCL Visual Control Library. But this is beyond the scope of this book, because this book is about the Pascal language.

Delphi's ninth lesson Windows programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.