Windows programming skills-Delphi

Source: Internet
Author: User
Tags intel pentium
Windows programming skills-Delphi

This article is collected and organized by lanyus. The technical source network in this article is part of this article, which is part of "Delphi of whimsical programming". For more information, see here.

// * Lanyus QQ: 231221 greathjw@163.com *///

1. Hide the taskbar
In Windows, the system's taskbar is essentially a window. Its window class is named "shell_traywnd ". To perform operations on it, you can use the API

Function findwindow and showwindow.

VaR
Wndhandle: thandle;
Wndclass: array [0 .. 50] of char;
Begin
Strpcopy (@ wndclass [0], 'Shell _ traywnd ');
Wndhandle: = findwindow (@ wndclass [0], nil );
Showwindow (wndhandle, sw_hide); // sw_restore
End;

Ii. Hide shortcuts on the desktop
Like the taskbar, the desktop is actually a window, and its class name is "progman". Similarly, you can use findwindow to find the window handle.

Showwindow to determine whether to display.

3. Obtain the taskbar size and position
Use findwindow to find the handle and getwindowrect to get the size of the current taskbar.
Getwindowrect (hwnd, // handle of the requested window
Lprect // address of the struct storing window coordinates
): Boolean;

4. Obtain CPU Information
CPU-related information is stored in a struct, which is encapsulated by DELPHI using tsysteminfo and is defined as follows:
Typedef struct_system_info {
Union {
DWORD dwoemid; // you have used the following struct branch to replace this variable.
Struct {
Word wprocessorarchitecture; // indicates the architecture of the processor.
Word wreserved; // Reserved Words
};
};
DWORD swpagesiae; // page size
Lpvoid lpminimumapplicationaddress; // The minimum address that can be accessed by applications and Dynamic Link Libraries
Lpvoid lpmaximumapplicationaddress; // The maximum address that can be accessed by applications and Dynamic Link Libraries
DWORD swactiveprocessormask; // mask of the active Processor
DWORD dwnumberofprocessors; // Number of processors
DWORD dwprocessortype; // processor category
DWORD dwallocationgranularity; // interval of Virtual Memory Address Allocation
Word wprocessorlevel; // processor level
Word wprocessorrevision; // processor modification Information
} System_info;
Dwprocessortype is determined by wprocessorarchitecture, wprocessorlevel, and wprocessorrevision.

The value is:
Processor_intel_386: intel80386 series;
Processor_itnel_: intel80486 series;
Processor_intel_pentium: Intel Pentium series;
Processor_mips_r4000: MIPS 4000 Series (applicable only to Windows NT );
Processor_alpha_21064: Alpha 21064 series (applicable only to Windows NT );

In addition, call the API function getsysteminfo to obtain CPU information.

5. Obtain memory information.
Like getting the CPU, the system still uses a struct to store memory information. The body definition that stores internal status information is as follows:
Typedef struct_memorystatus {
DWORD dwlength; // sizeof (memorystatus) indicates the size of the struct.
DWORD dwmemoryload; // current memory usage and total internal percentage
DWORD dwtotalphys; // total physical memory size
DWORD dwavailphys; // available physical memory size
DWORD dwtotalpagefile; // total page file size
DWORD dwavailpagefile; // Available page file size
DWORD dwtotalvirtual; // Total virtual memory size
DWORD dwavailvirtual; // available virtual memory size
} Memorystatus, * lpmemorystatus;

Finally, call the API function globalmemorystatus to obtain memory information.

6. Obtain the disk space. (Test findings are inaccurate)
Use the API function getdiskfreespace.
Bool getdiskfreespace (
Lpctstr lprootpathname, // root directory
Lpdword l1_ctorspercluster, // number of sectors per cluster
Lpdword lpbytespersector, // The number of bytes per slice
Lpdword lpnumberoffreeclusters, // number of available Clusters
Lpdword lptotalnumberofclusters // total number of clusters
);
Procedure tform1.bitbtn1click (Sender: tobject );
VaR
Secspclu, bytespsec, freeclu, totalclu, ts, FS: DWORD;
Begin
Getdiskfreespace ('C:/', secspclu, bytespsec, freeclu, totalclu );
FS: = freeclu * secspclu * bytespsec;
TS: = totalclu * secspclu * bytespsec;
Edit1.text: = formatfloat ('###,###', TS); // total space
Edit2.text: = formatfloat ('###,###', FS); // available space
End;

7. Restrict the mouse movement range.
In Windows, there is a ready-made API function clipcursor that can restrict the cursor moving area.
Bool clipcursor (
Const rect * lprect // point to a struct that stores rectangular range data
);
With this function, you can limit the moving range of the cursor on the screen. However, if you want to control the mouse movement within a fixed range of a window, you need to call

The mapwindowpoints function converts the coordinates of a form to the coordinates of another form.
Int mapwindowpoints (
Hwnd hwndfrom, // source window handle
Hwnd hwndto, // target form handle
Lppoint lppoints, // point to the struct array, containing the coordinates to be converted
Uint cpoints // Number of struct in the array
);
If the hwndform or hwndto parameter is null or hwnd_desktop, the source or target form is the screen form. The lppoints parameter can point to

Rect struct. The cpoints value is set to 2.

Procedure tform1.bitbtn1click (Sender: tobject );
VaR
SC: trect;
Begin
SC: = bitbtn2.boundsrect;
Mapwindowpoints (handle, 0, SC, 2 );
Clipcursor (@ SC );

End;

Procedure tform1.bitbtn2click (Sender: tobject );
VaR
SC: trect;
Begin
SC: = rect (0, 0, screen. Width, screen. Height );
Clipcursor (@ SC );
End;

8. How to start the screen saver.
Use the sendmessage or postmessage function.
Procedure tform1.bitbtn3click (Sender: tobject );
Begin
Sendmessage (hwnd_broadcast, wm_syscommand, SC _screensave, 0 );
End;
Another way to start the Screen Saver is to call the systemparametersinfo function to enable or disable the screen saver through its parameter settings.
Systemparametersinfo (spi_setscreensaveactive, 1, nil, 0); // enable screen saver
Systemparametersinfo (spi_setscreensaveactive, 0, nil, 0); // disable screen saver

9. Check whether the drive is ready.
In Delphi, no special function is provided to check whether the driver is ready or not, and one-person API function cannot be called directly to perform this operation. However, I

Disksize can be used to detect disk capacity. If the drive does not exist or is not ready, it will return-1. Otherwise, the disk or light will be returned.

Disk capacity.

Function disksize (drive: byte): int64;
If the parameter is set to 0, the current drive is specified. If the parameter is set to 1, disk A is used. If the parameter is set to 2, disk B is used.

10. Hide the mouse.
Use the showcursor function.
Int showcursor (
Bool bshow // indicates whether the cursor is visible
);
When the bshow parameter is set to false, the cursor is invisible. Note that calling this function only hides the mouse, and the program can still detect and trigger the mouse clicking or

Mobile events.

11. serial port operations.
No special serial port operation controls are provided in Delphi, so there is not much information about serial ports in the Help file. However, we can call

The Spcomm serial port control also works by calling a series of APIs.
Open the serial port using the API function createfile, which can open, create a file, or open a device. Its prototype is as follows:
Createfile (
Lpfilename: pchar; // indicates the file name or device name. The serial port is represented by COM1 and com2.
Dwdesiredaccess: DWORD; // access type. generic_read indicates read-only access, and generic_write indicates write access. Generic_read or

Generic_write indicates read/write access.
Dww.mode: DWORD; // specify the file sharing attribute. this parameter is provided for files shared by many applications and cannot be shared by serial ports,

It must be set to 0.
Lpsecurityattributes: psecurityattributes; // reference the Security Attribute security_attributes structure, which defines some

Properties, such as how the communication handle is inherited by the subroutine of the application that opens the port. If this parameter is set to null, a default security attribute is assigned to the port.
Dwcreationdisposition: DWORD; // specifies what to do when createfile is being called by an existing file. The serial port is a real object and must

Set it to open_existing. This flag tells windows not to create a new port, but to open an existing port.
Dwflagsandattributes: DWORD; // describes the attributes of the port. The only meaningful setting for the serial port is

File_flag_overlapped.
Htemplatefile: thandle // indicates the file handle. The serial port does not have a template file, so this parameter is set to 0.
): Thandle; stdcall;

Close the serial port and use the API function closehandle: closehandle (hobject: thandle): bool; stdccall; handle is createfile when the serial port is opened

The returned handle.
Initialize the serial port using the API function setupcomm: setupcomm (hfile: thandle; dwinqueue, dwoutqueue: DWORD): bool; stdcall;
Dwinqueue and dwoutqueue define the size of the receiving buffer and the sending buffer respectively (recommended only. The actual size is allocated by Windows );
Get the current configuration of the serial port: getcommstate (hfile: thandle; varlpdcb: tdcb): bool; stdcall; if the call is successful, a non-0 value is returned,

The getlasterror function can obtain error information.
.
Configure the serial port: setcommstate (hfile: thandle; const lpdcb: tdcb): bool; stdcall;
Get the serial port performance: getcomatrix roperties (hfile: thandle; var lpcomatrix drop: tcomatrix drop): bool; stdcall;
Communication Device Configuration: commconfigdialog (lpszname: pchar; hwnd: hwnd; var lpcc: tcommconfig); a configuration will pop up when you call this function.

Set window
Read serial port operation: readfile (hfile: thandle; var buffer; nnumberofbytestoread: DWORD; var

Lpnumberofbytesread: DWORD; lpoverlapped: poverlapped): bool; stdcall; supports synchronous or asynchronous operations.

12. List processes.
REFERENCE The tlhelp32 unit.
Create a system process snapshot by using the API function createconlhelp32snapshot, and use process32first to obtain the first system process.

Process32next: list them.

Procedure tform1.bitbtn13click (Sender: tobject); // Process Operation
VaR
Proname: string; // process name
Proid: integer; // process ID
Protheard: integer; // Number of process threads
Goloop: Boolean;
Fsnapshothandle: thandle; // system process snapshot handle
Fprocessentry32: tprocessentry32; // structure information of the Process entry
Begin
Fsnapshothandle: = createconlhelp32snapshot (th32cs_snapprocess, 0); // create a system process Snapshot
Fprocessentry32.dwsize: = sizeof (fprocessentry32 );
Goloop: = process32first (fsnapshothandle, fprocessentry32); // obtain the first process
While goloop do
Begin
Proname: = fprocessentry32.szexefile;
Proid: = fprocessentry32.th32processid;
Protheard: = fprocessentry32.cntthreads;
Listbox1.items. Add (proname + ''+ inttostr (proid) +'' + inttostr (protheard); // process is displayed in the ListBox group.

In
Goloop: = process32next (fsnapshothandle, fprocessentry32 );
End;

13. Run the program (RunAs) as another identity ).
Use the API function createprocesswithlogonw. This function is not fully encapsulated in Delphi and must be declared and defined before use.
Statement:
Function createprocesswithlogon (
Lpusername: pwchar; // account of user B)
Lpdomain: pwchar; // domain of user B)
Lppassword: pwchar; // password of user B)
Dwlogonflags: DWORD; // logon option
Lpapplicationname: pwchar; // the program to be run
Lpcommandline: pwchar; // command-line string
Dwcreationflags: DWORD; // creation flags
Lpenvironment: pointer; // New Environment Block
Lpcurrentdirectory: pwchar; // current directory name
Const lpstartupinfo: tstartupinfo; // startup information
VaR lpprocessinfo: tprocessinformation // Process Information
): Bool; stdcall;

Definition:
Function createprocesswithlogon; External advapi32 name 'createprocesswithlogonw ';

14. Obtain the current logon user name.
Use the API function GetUserName.
Procedure tform1.xp _ button2click (Sender: tobject); // obtain the current logon User Name
VaR
Users: array [0 .. 255] of char; // User Name
I: DWORD; // buffer size
Begin
If GetUserName (users, I) then
Edit6.text: = users;
End;

15. Modify the file creation time, modification time, and last access time.
You can use the API function setfiletime to directly modify the file creation time, modification time, and last access time. The API function getfiletime can be read.

File Creation Time, modification time, and last access time.
The two functions are as follows:

Function setfiletime (
Hfile: thandle; // file handle, which can be obtained by the createfile function to open the file
Lpcreationtime, // File Creation Time
Lplastaccesstime, // last access time
Lplastwritetime: pfiletime // last modification time
): Bool;

Function getfiletime (
Hfile: thandle; // file handle, which can be obtained by the createfile function to open the file
Lpcreationtime, // File Creation Time
Lplastaccesstime, // last access time
Lplastwritetime: pfiletime // last modification time
): Bool;
//////////////////////////////////////// //////////////////////////////
Hfileold: = createfile (srcfile, generic_read, file_assist_read, nil,
Open_existing, file_attribute_normal, Cardinal (NiL ));
Hfilenew: = createfile (destfile, generic_write, file_pai_write, nil,
Open_existing, file_attribute_normal, Cardinal (NiL ));
Getmem (creationtime, sizeof (tfiletime ));
Getmem (lastaccesstime, sizeof (tfiletime ));
Getmem (lastwritetime, sizeof (tfiletime ));
Getfiletime (hfileold, creationtime, lastaccesstime, lastwritetime );
Setfiletime (hfilenew, creationtime, lastaccesstime, lastwritetime );

16. Add the icon to the system tray.
You can add an icon in the system tray to send messages. In Windows, there is an API function shell_policyicon that can be used

Send messages to the tray.
Winshellapi bool winapi shell_policyicon (
DWORD dwmessage, // sent message
Pnotifyicondata pnid // point to the struct notifyicondata
);
It sends the following message parameters:
Nim_add // Add an icon to the tray
Nim_delete // delete an icon in the tray
Nim_modify // modify an icon in the tray
Another parameter is the pointer to notifyicondata, and notifyicondata is used to store the status bar information of system tasks.
Typedef struct_policyicondata {
DWORD cbsize; // the size of policyicondata.
Hwnd; // window handle for receiving tray mouse events
Uint uid; // The icon ID (wparam parameter of the tray mouse event)
Uint uflags; // valid range of the message
Uint ucallbackmessage; // the ID of the system return message
Hicon; // handle of the icon displayed in the tray
Char sztip [64]; // The prompt message when you move the cursor over the icon
} Notifyicondata, * ppolicyicondata;
Note: You must assign values to each member of the notifyicondata struct when installing the graph. Some members do not need to assign values when changing or deleting the struct.

17. Make the program appear on the System Task Bar
Procedure tform1.formcreate (Sender: tobject );
Begin
Setwindowlong (application. Handle, gwl_exstyle, ws_ex_toolwindow );
End;

Trackback: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 493088

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.