一、VC创建DLL
1. 选择“Win32 Dynamic-Link Library”类型;
2. 代码如下:
------------------------------------------------------------------------
// ShutDownPCDll.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "stdlib.h"
_declspec(dllexport) BOOL ShutDownPC(char *szAlertInfo, int nSecond,
BOOL boForceClose, BOOL boReboot);
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved )
{
return TRUE;
}
BOOL ShutDownPC(char *szAlertInfo, int nSecond, BOOL boForceClose, BOOL boReboot)
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
char szMachineName[64];
DWORD dwSize;
// 取本地机器名, 如"vinch"
if ( ! ::GetComputerName(szMachineName, &dwSize) )
{
//::MessageBox(NULL, "GetComputerName err", "", MB_OK);
return false;
}
// Get a token for this process.
if ( ! ::OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY, &hToken) )
{
//::MessageBox(NULL, "openprocesstoken err", "", MB_OK);
return false;
}
// Get the LUID for the shutdown privilege.
if ( ! ::LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid ) )
{
//::MessageBox(NULL, "LookupPrivilegeValue err", "", MB_OK);
return false;
}
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if ( ! ::AdjustTokenPrivileges(hToken, false, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0) )
{
//::MessageBox(NULL, "AdjustTokenPrivileges err", "", MB_OK);
return false;
}
// 6 -> 提示框倒计时6秒;如果为0,则无提示框,立即关闭。
if ( ! ::InitiateSystemShutdown(szMachineName, szAlertInfo, nSecond,
boForceClose, boReboot) )
{
//::MessageBox(NULL, "InitiateSystemShutdown err", szMachineName, MB_OK);
return false;
}
return true;
}
------------------------------------------------------------------------
3. 新建Def文件,加入函数声明 “EXPORTS ShutDownPC”。 OK.
二、在Delphi调用中调用
代码如下:
--------------------------------------------------------------------
type
TFunc1 = function(szAlertInfo: Pchar; nSecond: Integer;
boForceClose, boReboot: Boolean): Boolean; cdecl;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
procedure p_ShutDownPC;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.p_ShutDownPC;
var
hDLL: THandle;
f1: TFunc1;
begin
hDLL := LoadLibrary( Pchar(ExtractFilePath(Application.ExeName)
+ 'ShutDownPCDll.dll') );
if ( hDLL <> 0 ) then
begin
f1 := GetProcAddress(hDLL, 'ShutDownPC');
// 倒数30秒关机
if ( not f1( Pchar('test by wf'), 30, false, false) ) then
ShowMessage('shut err');
FreeLibrary(hDLL);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
p_ShutDownPC();
end;
end.
--------------------------------------------------------------------
最后,将vc下编译生成的dll拷到delphi工程目录下,即可运行。
ps: 在定义函数类型时,一定要加上cdecl。若不写或者写成stdcall,则错。