RSS订阅 | 匿名投稿
您的位置:网站首页 > 程序 > 正文

Delphi自动以管理员身份在vista 和 windows7 下运行程序

作者:admin 来源:未知 日期:2010/1/27 8:53:08 人气: 标签:

Tags 关键字:Delphi,管理员身份

unit Unit1;

interface

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

type
TForm1 = class(TForm)

procedure FormCreate(Sender:TObject);
private
{Private declarations}
public
{Public declarations}
end;

type
_STARTUPINFOW=record
cb:DWORD;
lpReserved:LPWSTR;
lpDesktop:LPWSTR;
lpTitle:LPWSTR;
dwX:DWORD;
dwY:DWORD;
dwXSize:DWORD;
dwYSize:DWORD;
dwXCountChars:DWORD;
dwYCountChars:DWORD;
dwFillAttribute:DWORD;
dwFlags:DWORD;
wShowWindow:Word;
cbReserved2:Word;
lpReserved2:PByte;
hStdInput:THandle;
hStdOutput:THandle;
hStdError:THandle;
end;
STARTUPINFOW=_STARTUPINFOW;

function CreateProcessWithLogonW(lpUserName,lpDomain,lpPassword:LPCWSTR;
dwLogonFlags:DWORD;lpApplicationName: LPCWSTR; lpCommandLine: LPWSTR;
dwCreationFlags: DWORD; lpEnvironment: Pointer; lpCurrentDirectory: LPCWSTR;
const lpStartupInfo:STARTUPINFOW;
var lpProcessInformation:PROCESS_INFORMATION):BOOL; stdcall;
external advapi32 Name 'CreateProcessWithLogonW'
var
Form1:TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
STARTUPINFO:StartupInfoW;
ProcessInfo:TProcessInformation;
AUser,ADomain,APass,AExe:WideString;
const
LOGON_WITH_PROFILE = $00000001;
LOGON_NETCREDENTIALS_ONLY = $00000002;
begin
FillChar(STARTUPINFO,SizeOf(StartupInfoW),#0);
STARTUPINFO.cb := SizeOf(StartupInfoW);
STARTUPINFO.dwFlags := STARTF_USESHOWWINDOW;
STARTUPINFO.wShowWindow := SW_SHOW;
AUser:='administrator'; //账户名
ADomain:='abc'; //如果有域则写上域名
APass:='123'; //密码
AExe:='Sub.exe'; //要运行的程序
if not CreateProcessWithLogonW(PWideChar(AUser),PWideChar(ADomain),PWideChar(APass),
LOGON_WITH_PROFILE,nil,PWideChar(AExe),
NORMAL_PRIORITY_CLASS, nil,nil,STARTUPINFO,ProcessInfo)then
showmessage('密码错误!');//RaiseLastOSError;
//WaitForSingleObject(ProcessInfo.hProcess,INFINITE); //等待执完毕
application.Terminate;
end;
end.


另一种方法,操作步骤如下:

1.建立 res 文件

建立一个文本文件,名字可以自己起,如UAC.manifest,内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>


建立文本文件,名为 UAC.rc,内容:

1 24 UAC.manifest
编译成 uac.res 文件,运行:

brcc32 uac.rc -fouac.res
2.在代码中引入
打开项目文件,加入

{$R uac.res}
3.编译程序

这时程序就支持 VISTA 了,在运行的时候,会弹出 WINDOWS 的提示框,询问用户是否允许以管理员身份运行。
读完这篇文章后,您心情如何?
0
0
0
0
0
0
0
0
本文网址: