本文深入解析"其他源码光盘1"中的经典Delphi实例,展示每个示例的核心源代码和关键技术实现。通过详细的代码分析,帮助开发者理解这些经典解决方案的实现原理。
完整的数据库连接管理和操作框架,封装了ADO组件的核心功能。
type
TConnection = class
private
FADOConnection: TADOConnection;
function ConstructorConnStr: string;
public
constructor Create(LoginPrompt: Boolean);
property ADOConnection: TADOConnection read FADOConnection;
end;
constructor TConnection.Create(LoginPrompt: Boolean);
begin
inherited Create;
FADOConnection := TADOConnection.Create(nil);
FADOConnection.ConnectionString := ConstructorConnStr;
FADOConnection.LoginPrompt := LoginPrompt;
try
FADOConnection.Open;
except
on E: Exception do
raise Exception.Create('数据库连接失败: ' + E.Message);
end;
end;
function TConnection.ConstructorConnStr: string;
begin
// 构造连接字符串
Result := 'Provider=SQLOLEDB.1;Integrated Security=SSPI;'+
'Persist Security Info=False;Initial Catalog=TestDB;'+
'Data Source=localhost';
end;type
TADOCommonQuery = class(TObject)
private
FADOQuery: TADOQuery;
FParameters: TParameters;
public
procedure ImportQryParam(sSqlStatement: string;
ArgName: array of string; ArgValue: array of Const);
function GetADOQuery: TADOQuery;
property NoRowSelected: Boolean read Get_NoRowSelected;
end;
procedure TADOCommonQuery.ImportQryParam(sSqlStatement: string;
ArgName: array of string; ArgValue: array of Const);
var
i: Integer;
begin
FADOQuery.Close;
FADOQuery.SQL.Text := sSqlStatement;
// 设置参数
for i := 0 to High(ArgName) do
begin
FADOQuery.Parameters.ParamByName(ArgName[i]).Value := ArgValue[i];
end;
FADOQuery.Open;
end;使用DBISAM组件创建和管理数据库表的完整示例。
procedure CreateTables(CreateDatabaseName: string);
var
TableToCreate: TDBISAMTable;
StopWords: TStrings;
begin
TableToCreate:=TDBISAMTable.Create(Application);
try
with TableToCreate do
begin
DatabaseName:=CreateDatabaseName;
TableName:='animals';
Exclusive:=True;
// 定义字段结构
with FieldDefs do
begin
Clear;
Add('NAME',ftString,30,False);
Add('SIZE',ftSmallint,0,False);
Add('WEIGHT',ftSmallint,0,False);
Add('AREA',ftString,20,False);
Add('BMP',ftGraphic,0,False);
end;
// 定义索引
with IndexDefs do
begin
Clear;
Add('NAME','NAME',[]);
end;
if not Exists then
begin
CreateTable;
// 表结构重组和优化
RestructureTable(0,0,3,12,False,'','',512,-1,'',
StopWords, '*+,-./:;<=>\`',
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz',
True);
end;
end;
finally
TableToCreate.Free;
end;
end;使用Windows API获取和管理系统进程信息的核心实现。
procedure TForm1.GetProcesses;
var
hSnap: THandle;
ProcessEntry: TProcessEntry32;
Proceed: Boolean;
begin
// 创建系统快照
hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if HSnap <> INVALID_HANDLE_VALUE then
begin
ProcessEntry.dwSize := SizeOf(TProcessEntry32);
Proceed := Process32First(hSnap, ProcessEntry);
while Proceed do
begin
with ProcessEntry do
with ListView_pro.Items.Add do
begin
Caption := szEXEFile; // 进程名称
SubItems.Add(IntToStr(Th32ProcessID)); // 进程ID
SubItems.Add(IntToStr(th32ParentProcessID)); // 父进程ID
SubItems.Add(IntToStr(Th32ModuleID)); // 模块ID
SubItems.Add(IntToStr(cntUsage)); // 引用计数
SubItems.Add(IntToStr(cntThreads)); // 线程数
SubItems.Add(IntToStr(pcPriClassBase)); // 优先级
end;
Proceed := Process32Next(hSnap, ProcessEntry);
end;
CloseHandle(hSnap);
end
else
ShowMessage('无法创建系统快照: ' + SysErrorMessage(GetLastError));
end;procedure TForm1.GetModules(ProcessID: DWORD);
var
hSnap: THandle;
ModuleEntry: TModuleEntry32;
Proceed: Boolean;
begin
hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessID);
if HSnap <> INVALID_HANDLE_VALUE then
begin
ModuleEntry.dwSize := SizeOf(TModuleEntry32);
Proceed := Module32First(hSnap, ModuleEntry);
while Proceed do
begin
with ModuleEntry do
with ListView_mod.Items.Add do
begin
Caption := szModule; // 模块名称
SubItems.Add(ExtractFilePath(szEXEPath)); // 路径
SubItems.Add(IntToStr(Th32ModuleID)); // 模块ID
SubItems.Add(FloatToStr(ModBaseSize/1024)); // 大小(KB)
SubItems.Add(IntToStr(GlblCntUsage)); // 全局引用计数
end;
Proceed := Module32Next(hSnap, ModuleEntry);
end;
CloseHandle(hSnap);
end
else
ShowMessage('无法获取模块信息: ' + SysErrorMessage(GetLastError));
end;procedure TForm1.SpeedButton3Click(Sender: TObject);
var
uexitcode: byte;
ProcessHandle: THandle;
begin
if ListView_pro.Selected <> nil then
begin
if MessageDlg('终止进程可能导致系统不稳定!确认吗?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
ProcessHandle := OpenProcess(PROCESS_TERMINATE, False,
StrToInt(ListView_pro.Selected.SubItems[0]));
if ProcessHandle <> 0 then
begin
TerminateProcess(ProcessHandle, uexitcode);
ListView_pro.Selected.Delete;
StatusBar1.Panels[0].Text := '系统进程数:' +
IntToStr(ListView_pro.Items.Count);
CloseHandle(ProcessHandle);
end
else
ShowMessage('无法打开进程句柄');
end;
end
else
ShowMessage('请选择一个进程!');
end;创建无边框自定义窗口的核心技术实现。
program Normal;
uses
UnitDllExe in 'UnitDllExe.pas',
Forms,
FormMain in 'FormMain.pas' {MainForm};
{$R *.res}
begin
Application.Initialize;
Application.CreateForm(TMainForm, MainForm);
// 关键:将应用程序句柄设置为窗体句柄
Application.Handle := MainForm.Handle;
Application.Run;
end.unit UnitDllExe; interface implementation initialization // 设置是否为库模式 IsLibrary := true; end.
基于IE内核的Web浏览器组件开发。
unit MainFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, SHDocVw_TLB, ZoCWebBrowser;
type
TMainForm = class(TForm)
ZoCWebBrowser: TZoCWebBrowser;
function ZoCWebBrowserGetExternal(out ppDispatch: IDispatch): HRESULT;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
uses MyExternalImpl;
function TMainForm.ZoCWebBrowserGetExternal(
out ppDispatch: IDispatch): HRESULT;
var
MyExternal: TMyExternal;
begin
MyExternal := TMyExternal.Create;
ppDispatch := MyExternal;
Result := S_OK;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
// 初始化Web浏览器
ZoCWebBrowser.Navigate('http://www.example.com');
end;串口数据收发的基础框架代码。
type
TSerialPort = class
private
FHandle: THandle;
FPortName: string;
FBaudRate: DWORD;
public
function OpenPort(PortName: string; BaudRate: DWORD): Boolean;
function ClosePort: Boolean;
function WriteData(Buffer: Pointer; Count: DWORD): DWORD;
function ReadData(Buffer: Pointer; Count: DWORD): DWORD;
end;
function TSerialPort.OpenPort(PortName: string; BaudRate: DWORD): Boolean;
var
CommTimeouts: TCommTimeouts;
begin
FPortName := PortName;
FBaudRate := BaudRate;
// 打开串口
FHandle := CreateFile(PChar('\\.\' + PortName),
GENERIC_READ or GENERIC_WRITE,
0, nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
if FHandle = INVALID_HANDLE_VALUE then
begin
Result := False;
Exit;
end;
// 配置串口参数
SetupComm(FHandle, 4096, 4096);
// 设置超时
CommTimeouts.ReadIntervalTimeout := MAXDWORD;
CommTimeouts.ReadTotalTimeoutMultiplier := 0;
CommTimeouts.ReadTotalTimeoutConstant := 0;
CommTimeouts.WriteTotalTimeoutMultiplier := 0;
CommTimeouts.WriteTotalTimeoutConstant := 5000;
SetCommTimeouts(FHandle, CommTimeouts);
Result := True;
end;批量文件处理和管理的基础实现。
type
TFileProcessor = class
private
FSourcePath: string;
FDestPath: string;
public
procedure BatchRename(const FileMask: string; const NewNamePattern: string);
procedure CopyFiles(const FileMask: string; const DestFolder: string);
function GetFileSize(const FileName: string): Int64;
end;
procedure TFileProcessor.BatchRename(const FileMask: string;
const NewNamePattern: string);
var
SearchRec: TSearchRec;
Counter: Integer;
NewName: string;
begin
Counter := 1;
if FindFirst(FSourcePath + FileMask, faAnyFile, SearchRec) = 0 then
begin
repeat
if (SearchRec.Attr and faDirectory) = 0 then
begin
NewName := Format(NewNamePattern, [Counter]);
RenameFile(FSourcePath + SearchRec.Name,
FSourcePath + NewName);
Inc(Counter);
end;
until FindNext(SearchRec) <> 0;
FindClose(SearchRec);
end;
end;
function TFileProcessor.GetFileSize(const FileName: string): Int64;
var
Handle: THandle;
FindData: TWin32FindData;
begin
Handle := FindFirstFile(PChar(FileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then
begin
Result := Int64(FindData.nFileSizeHigh) shl 32 or
Int64(FindData.nFileSizeLow);
Windows.FindClose(Handle);
end
else
Result := -1;
end;这些经典实例的源代码展现了Delphi开发者解决实际问题的技术智慧。每个示例都体现了: