几个在Delphi 中取本机的计算机名、IP地址、Windows登录的用户名的函数. uses Windows, WinSock; { ComputerLocalIP } //取本机的 IP 地址 function ComputerLocalIP: string; var ch: array[1..32] of char; wsData: TWSAData; myHost: PHostEnt; i: integer; begin Result := ''; if WSAstartup(2,wsData)<>0 then Exit; // can’t start winsock try if GetHostName(@ch[1],32)<>0 then Exit; // getHostName failed except Exit; end; myHost := GetHostByName(@ch[1]); // GetHostName error if myHost=nil then exit; for i:=1 to 4 do begin Result := Result + IntToStr(Ord(myHost.h_addr^[i-1])); if i<4 then Result := Result + '.'; end; end; //取本机的计算机名 { ComputerName } function ComputerName: string; var FStr: PChar; FSize: Cardinal; begin FSize := 255; GetMem(FStr, FSize); Windows.GetComputerName(FStr, FSize); Result := FStr; FreeMem(FStr); end; //取Windows登录用户名 { WinUserName } function WinUserName: string; var FStr: PChar; FSize: Cardinal; begin FSize := 255; GetMem(FStr, FSize); GetUserName(FStr, FSize); Result := FStr; FreeMem(FStr); end;
1.1:Delphi获取计算机名
procedure TMainForm.tmrMonitorTimer(Sender: TObject); var ComputerName:array[0..MAX_COMPUTERNAME_LENGTH+1] of char; //保留计算机名的缓冲区 Buffer:Dword; // 缓冲区大小 sComputerName:string;//计算机名 begin Buffer:=MAX_COMPUTERNAME_LENGTH+1; if GetComputerName(@ComputerName,Buffer) then begin sComputerName:=ComputerName; end else begin sComputerName:=''; end; ShowMessage(sComputerName); end;
1.2: 取得计算机名(delphi )
//------非常简单------------------------ procedure TForm2.Button2Click(Sender: TObject); var s: Cardinal; p: PChar; begin s := MAX_COMPUTERNAME_LENGTH + 1; GetMem(p, s); if GetComputerName(p,s) then begin caption := StrPas(p); end else ShowMessage('取不到计算机名'); FreeMem(p); //记得一定要释放 end;
关于取本地计算机的IP地址及计算机名的看法 大体步骤:
需要用到一个组件,TCPClient 或直接引用:Web.Win.Sockets 1:先创建一个窗体。 2:将一个label1,一个按扭 bitbtn1,bittn2 放入窗体。 3:对BITBTN1 的ONCLICK 事件编程。 编程如下: ....... var tp:ttcpclient; strname,straddr:string; begin tp:=ttcpclient.create(self); tp.close; tp.open; strname:=tp.LocalHostName; straddr:=tp.LocalHostAddr; label1.caption:=strname+' IP: '+straddr; tp.close; end; bitbtn2 的onclick 事件如下: ..... begin close; end; 如上程序,运行后,单击bitbtn1 按扭, label1 将显示出本地计算机的 IP地址 和计算机名。(完毕)
----
我修改了下,以后就用第二种方法了,真是方便:
var MyTcpClient: TTcpClient; LocalHostName,LocalHostAddr:string; begin MyTcpClient := TTcpClient.create(self); try LocalHostName := string(MyTcpClient.LocalHostName); LocalHostAddr := string(MyTcpClient.LocalHostAddr); finally MyTcpClient.Free; end; end;
2012.07.24补充---------我自己用的:UFastWindowsApi单元:
function TFastWindowsApi.GetComputerNameIpListStr: string; var MyTcpClient: TTcpClient; LocalHostName,LocalHostAddr:string; begin MyTcpClient := TTcpClient.create(nil); try LocalHostName := string(MyTcpClient.LocalHostName); LocalHostAddr := string(MyTcpClient.LocalHostAddr); //返回 Exit(LocalHostName+','+LocalHostAddr); finally MyTcpClient.Free; end; end;
本文来自博客园,作者:del88,转载请注明原文链接:https://www.cnblogs.com/del88/archive/2012/07/24/2606087.html
浙公网安备 33010602011771号