Delphi 与操作系统相关的一些方法

前言

Delphi 提供了一些与操作系统相关的操作,我这里给大家整理了一下,希望有所帮助。

1.获取CPU序列号

unit Main;

interface

uses Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, ExtCtrls, StdCtrls, Buttons;

type
TDemoForm = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
GetButton: TBitBtn;
CloseButton: TBitBtn;
Bevel1: TBevel;
Label5: TLabel;
FLabel: TLabel;
MLabel: TLabel;
PLabel: TLabel;
SLabel: TLabel;
PValue: TLabel;
FValue: TLabel;
MValue: TLabel;
SValue: TLabel;
procedure GetButtonClick(Sender: TObject);
end;

var
DemoForm: TDemoForm;

implementation

{$R *.DFM}

const
ID_BIT = $200000; // EFLAGS ID bit
type
TCPUID = array[1..4] of Longint;
TVendor = array [0..11] of char;

function IsCPUID_Available : Boolean; register;
asm
PUSHFD {direct access to flags no possible, only via stack}
POP EAX {flags to EAX}
MOV EDX,EAX {save current flags}
XOR EAX,ID_BIT {not ID bit}
PUSH EAX {onto stack}
POPFD {from stack to flags, with not ID bit}
PUSHFD {back to stack}
POP EAX {get back to EAX}
XOR EAX,EDX {check if ID bit affected}
JZ @exit {no, CPUID not availavle}
MOV AL,True {Result=True}
@exit:
end;

function GetCPUID : TCPUID; assembler; register;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Resukt}
MOV EAX,1
DW $A20F {CPUID Command}
STOSD {CPUID[1]}
MOV EAX,EBX
STOSD {CPUID[2]}
MOV EAX,ECX
STOSD {CPUID[3]}
MOV EAX,EDX
STOSD {CPUID[4]}
POP EDI {Restore registers}
POP EBX
end;

function GetCPUVendor : TVendor; assembler; register;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Result (TVendor)}
MOV EAX,0
DW $A20F {CPUID Command}
MOV EAX,EBX
XCHG EBX,ECX {save ECX result}
MOV ECX,4
@1:
STOSB
SHR EAX,8
LOOP @1
MOV EAX,EDX
MOV ECX,4
@2:
STOSB
SHR EAX,8
LOOP @2
MOV EAX,EBX
MOV ECX,4
@3:
STOSB
SHR EAX,8
LOOP @3
POP EDI {Restore registers}
POP EBX
end;

procedure TDemoForm.GetButtonClick(Sender: TObject);
var
CPUID : TCPUID;
I : Integer;
S : TVendor;
begin
for I := Low(CPUID) to High(CPUID) do CPUID := -1;
if IsCPUID_Available then begin
CPUID := GetCPUID;
Label1.Caption := 'CPUID[1] = ' + IntToHex(CPUID[1],8);
Label2.Caption := 'CPUID[2] = ' + IntToHex(CPUID[2],8);
Label3.Caption := 'CPUID[3] = ' + IntToHex(CPUID[3],8);
Label4.Caption := 'CPUID[4] = ' + IntToHex(CPUID[4],8);
PValue.Caption := IntToStr(CPUID[1] shr 12 and 3);
FValue.Caption := IntToStr(CPUID[1] shr 8 and $f);
MValue.Caption := IntToStr(CPUID[1] shr 4 and $f);
SValue.Caption := IntToStr(CPUID[1] and $f);
S := GetCPUVendor;
Label5.Caption := 'Vendor: ' + S; end
else begin
Label5.Caption := 'CPUID not available';
end;
end;

end.
 

2.Delphi获得当前所有进程名,进程PID

// 获取系统当前进程名和进程ID,
//注:应引用"TLHelp32"单元"use TLHelp32"。
unit Unit2;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls,TLHelp32;

type
TForm2 = class(TForm)
    ListBox1: TListBox;
    ListView1: TListView;
    Button1: TButton;
    Button2: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
private
    { Private declarations }
public
    { Public declarations }
end;

var
Form2: TForm2;
ContinueLoop:BOOL;       //是否继续循环
FSnapshotHandle:THandle; //进程快照句柄
FProcessEntry32:TProcessEntry32; //进程入口的结构体信息

implementation

{$R *.dfm}

procedure TForm2.Button1Click(Sender: TObject);
//在listview中显示进程
var
NewItem: TListItem;
Summ:integer;
begin
ListView1.Items.BeginUpdate;
ListView1.Items.Clear;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
//CreateToolhelp32Snapshot函数得到进程快照
FProcessEntry32.dwSize := Sizeof(FProcessEntry32); //初始化
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
//Process32First 得到一个系统快照里第一个进程的信息
Summ := 0;
while ContinueLoop do
    begin
    Summ := Summ + 1;
   NewItem := ListView1.Items.Add;   //在ListView1显示
   NewItem.ImageIndex := -1;
    NewItem.Caption := ExtractFileName(FProcessEntry32.szExeFile); //进程名称
    //??NewItem.Caption := ExtractFilePath(FProcessEntry32.szExeFile);//进程名称
   NewItem.subItems.Add(FormatFloat('00', Summ));//序号
   NewItem.subItems.Add(IntToStr(FProcessEntry32.th32ProcessID));//进程ID
   ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
ListView1.Items.EndUpdate;

Label1.Caption:='进程数:'+inttostr(ListView1.Items.Count);

end;

procedure TForm2.Button2Click(Sender: TObject);
//在listbox中显示进程 id
var
ProcessName : string; //进程名
ProcessID : integer; //进程表示符
begin
FSnapshotHandle:=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); //创建一个进程快照
FProcessEntry32.dwSize:=Sizeof(FProcessEntry32);
ContinueLoop:=Process32First(FSnapshotHandle,FProcessEntry32); //得到系统中第一个进程
//循环例举
while ContinueLoop do
begin
    ProcessName := FProcessEntry32.szExeFile;
    ProcessID := FProcessEntry32.th32ProcessID;
    Listbox1.Items.add('应用程序名 :'+ProcessName +'#进程ID:'+ inttostr(ProcessID));
    ContinueLoop:=Process32Next(FSnapshotHandle,FProcessEntry32);
end;
end;

procedure TForm2.FormCreate(Sender: TObject);

begin
//对ListView1的初始化
ListView1.ViewStyle:=vsReport; //设置ListView的显示方式 不设置这种方式不显示列头
ListView1.Columns.Add;       //添加第一列
ListView1.Column[0].Caption:='进程名';
ListView1.Column[0].AutoSize:=false;
ListView1.Column[0].Width:=100;
ListView1.Column[0].Alignment:=taLeftJustify;//左对齐
ListView1.Columns.Add;       //添加第二列
ListView1.Column[ListView1.Columns.Count-1].Caption:='序号';
ListView1.Column[ListView1.Columns.Count-1].AutoSize:=true;
ListView1.Column[ListView1.Columns.Count-1].Alignment:=taLeftJustify;//左对齐
ListView1.Columns.Add;       //添加第三列
ListView1.Column[ListView1.Columns.Count-1].Caption:='ID';
ListView1.Column[ListView1.Columns.Count-1].AutoSize:=true;
ListView1.Column[ListView1.Columns.Count-1].Alignment:=taLeftJustify;//左对齐



end;
end.

3.delphi获得某个磁盘或是文件夹的所有子目录

该函数用来获得某个磁盘或是某个文件下所有文件夹
function GetDirList(pPath: String): TStringList;
var
  SearchRec:TSearchRec;
  i:Integer;
  lStringList:TStringList;
  TempPath:string;
begin
  lStringList:=TStringList.Create;
  TempPath:=pPath+'\*.*';
  i:=FindFirst(TempPath,faDirectory,SearchRec);
  while i=0 do
  begin
    if SearchRec.Attr=16 then
    begin
      if (SearchRec.Name<>'.')and(SearchRec.Name<>'..') then
        lStringList.Add(SearchRec.Name);
    end;
    i:= FindNext(SearchRec);
  end;
  FindClose(SearchRec);
  Result:=lStringList;
end;
该函数用来得到某个磁盘或是文件夹下的所有文件夹包括子文件夹。
function TForm1.GetDirTreeList(pPath: String): TStringList;
var
  SearchRec:TSearchRec;
  i:Integer;
  TempStringList,lStringList:TStringList;
  TempPath:string;
begin
  lStringList:=TStringList.Create;
  TempPath:=pPath+'\*.*';
  i:=FindFirst(TempPath,faDirectory,SearchRec);
  while i=0 do
  begin
    if SearchRec.Attr=16 then
    begin
      if (SearchRec.Name<>'.') and (SearchRec.Name<>'..') then
      begin
        lStringList.Add(pPath+'\'+SearchRec.Name);
        TempStringList:=GetDirTreeList(pPath+'\'+SearchRec.Name);
        lStringList.Text:=lStringList.Text+TempStringList.Text;
      end;
    end;
    i:= FindNext(SearchRec);
  end;
  Result:=lStringList;
end;
至于怎么加密以后在慢慢贴上。不过大体思路就是:加密的时候从内到位,解密的时候从外到内

4.DELPHI获取网卡MAC地址

DELPHI获取网卡MAC地址
1、通过IP取MAC地址

uses
WinSock;

Function sendarp(ipaddr:ulong;
temp:dword;
ulmacaddr:pointer;
ulmacaddrleng:pointer) : DWord; StdCall; External 'Iphlpapi.dll' Name 'SendARP';

procedure TForm1.Button1Click(Sender: TObject);
var
myip:ulong;
mymac:array[0..5] of byte;
mymaclength:ulong;
r:integer;
begin
myip:=inet_addr(PChar('192.168.6.180'));
mymaclength:=length(mymac);
r:=sendarp(myip,0,@mymac,@mymaclength);
label1.caption:='errorcode:'+inttostr(r);
label2.caption:=format('%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x',[mymac[0],mymac[1],mymac[2],mymac[3],mymac[4],mymac[5]]);
end; 


2、取MAC地址 (含多网卡)

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
WinSock, StdCtrls;

Const
MAX_HOSTNAME_LEN = 128; { from IPTYPES.H }
MAX_DOMAIN_NAME_LEN = 128;
MAX_SCOPE_ID_LEN = 256;
MAX_ADAPTER_NAME_LENGTH = 256;
MAX_ADAPTER_DESCRIPTION_LENGTH = 128;
MAX_ADAPTER_ADDRESS_LENGTH = 8;

Type
TIPAddressString = Array[0..4*4-1] of Char;

PIPAddrString = ^TIPAddrString;
TIPAddrString = Record
Next : PIPAddrString;
IPAddress : TIPAddressString;
IPMask : TIPAddressString;
Context : Integer;
End;

PFixedInfo = ^TFixedInfo;
TFixedInfo = Record { FIXED_INFO }
HostName : Array[0..MAX_HOSTNAME_LEN+3] of Char;
DomainName : Array[0..MAX_DOMAIN_NAME_LEN+3] of Char;
CurrentDNSServer : PIPAddrString;
DNSServerList : TIPAddrString;
NodeType : Integer;
ScopeId : Array[0..MAX_SCOPE_ID_LEN+3] of Char;
EnableRouting : Integer;
EnableProxy : Integer;
EnableDNS : Integer;
End;

PIPAdapterInfo = ^TIPAdapterInfo;
TIPAdapterInfo = Record { IP_ADAPTER_INFO }
Next : PIPAdapterInfo;
ComboIndex : Integer;
AdapterName : Array[0..MAX_ADAPTER_NAME_LENGTH+3] of Char;
Description : Array[0..MAX_ADAPTER_DESCRIPTION_LENGTH+3] of Char;
AddressLength : Integer;
Address : Array[1..MAX_ADAPTER_ADDRESS_LENGTH] of Byte;
Index : Integer;
_Type : Integer;
DHCPEnabled : Integer;
CurrentIPAddress : PIPAddrString;
IPAddressList : TIPAddrString;
GatewayList : TIPAddrString;
DHCPServer : TIPAddrString;
HaveWINS : Bool;
PrimaryWINSServer : TIPAddrString;
SecondaryWINSServer : TIPAddrString;
LeaseObtained : Integer;
LeaseExpires : Integer;
End;

type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure GetAdapterInformation;
public
{ Public declarations }
end;

var
Form1: TForm1;

Function sendarp(ipaddr:ulong;
temp:dword;
ulmacaddr:pointer;
ulmacaddrleng:pointer) : DWord; StdCall;

implementation

{$R *.dfm}

Function sendarp; External 'Iphlpapi.dll' Name 'SendARP';
Function GetAdaptersInfo(AI : PIPAdapterInfo; Var BufLen : Integer) : Integer;
StdCall; External 'iphlpapi.dll' Name 'GetAdaptersInfo';

procedure TForm1.GetAdapterInformation;
Var
AI,Work : PIPAdapterInfo;
Size : Integer;
Res : Integer;
I : Integer;

Function MACToStr(ByteArr : PByte; Len : Integer) : String;
Begin
Result := '';
While (Len > 0) do Begin
Result := Result+IntToHex(ByteArr^,2)+'-';
ByteArr := Pointer(Integer(ByteArr)+SizeOf(Byte));
Dec(Len);
End;
SetLength(Result,Length(Result)-1); { remove last dash }
End;

Function GetAddrString(Addr : PIPAddrString) : String;
Begin
Result := '';
While (Addr <> nil) do Begin
Result := Result+'A: '+Addr^.IPAddress+' M: '+Addr^.IPMask+#13;
Addr := Addr^.Next;
End;
End;

Function TimeTToDateTimeStr(TimeT : Integer) : String;
Const UnixDateDelta = 25569; { days between 12/31/1899 and 1/1/1970 }
Var
DT : TDateTime;
TZ : TTimeZoneInformation;
Res : DWord;

Begin
If (TimeT = 0) Then Result := ''
Else Begin
{ Unix TIME_T is secs since 1/1/1970 }
DT := UnixDateDelta+(TimeT / (24*60*60)); { in UTC }
{ calculate bias }
Res := GetTimeZoneInformation(TZ);
If (Res = TIME_ZONE_ID_INVALID) Then RaiseLastWin32Error;
If (Res = TIME_ZONE_ID_STANDARD) Then Begin
DT := DT-((TZ.Bias+TZ.StandardBias) / (24*60));
Result := DateTimeToStr(DT)+' '+WideCharToString(TZ.StandardName);
End
Else Begin { daylight saving time }
DT := DT-((TZ.Bias+TZ.DaylightBias) / (24*60));
Result := DateTimeToStr(DT)+' '+WideCharToString(TZ.DaylightName);
End;
End;
End;

begin
Memo1.Lines.Clear;
Size := 5120;
GetMem(AI,Size);
Res := GetAdaptersInfo(AI,Size);
If (Res <> ERROR_SUCCESS) Then Begin
SetLastError(Res);
RaiseLastWin32Error;
End;
With Memo1,Lines do Begin
Work := AI;
I := 1;
Repeat
Add('');
Add('Adapter ' + IntToStr(I));
Add(' ComboIndex: '+IntToStr(Work^.ComboIndex));
Add(' Adapter name: '+Work^.AdapterName);
Add(' Description: '+Work^.Description);
Add(' Adapter address: '+MACToStr(@Work^.Address,Work^.AddressLength));
Add(' Index: '+IntToStr(Work^.Index));
Add(' Type: '+IntToStr(Work^._Type));
Add(' DHCP: '+IntToStr(Work^.DHCPEnabled));
Add(' Current IP: '+GetAddrString(Work^.CurrentIPAddress));
Add(' IP addresses: '+GetAddrString(@Work^.IPAddressList));
Add(' Gateways: '+GetAddrString(@Work^.GatewayList));
Add(' DHCP servers: '+GetAddrString(@Work^.DHCPServer));
Add(' Has WINS: '+IntToStr(Integer(Work^.HaveWINS)));
Add(' Primary WINS: '+GetAddrString(@Work^.PrimaryWINSServer));
Add(' Secondary WINS: '+GetAddrString(@Work^.SecondaryWINSServer));
Add(' Lease obtained: '+TimeTToDateTimeStr(Work^.LeaseObtained));
Add(' Lease expires: '+TimeTToDateTimeStr(Work^.LeaseExpires));
Inc(I);
Work := Work^.Next;
Until (Work = nil);
End;
FreeMem(AI);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
GetAdapterInformation;
end;

end.

方法2

uses nb30;

function NBGetAdapterAddress(a: Integer): string;
var
NCB: TNCB; // Netbios control block //NetBios控制块
ADAPTER: TADAPTERSTATUS; // Netbios adapter status//取网卡状态
LANAENUM: TLANAENUM; // Netbios lana
intIdx: Integer; // Temporary work value//临时变量
cRC: C

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值