分类 [ 学习编程 ] 下的全部文章


  前两天看了Delphi版面精华区中的《进程死亡的自动复活》一文,觉得作者的思路很不错,利用api来监视进程的活动,当被销毁时就自动再创建进程。仔细推敲之后,发觉其实用vb也是可以做到的。于是花了半天的时间写了以下的程序,实现了使用WaitForSingleObject API来监视被创建的进程的活动,一旦返回除 time out 之外的消息就自动创建新的进程。以下为其实现代码。在 win2000 server + vb 6.0下通过。

Option Explicit

Private RunFile$

Private Const NORMAL_PRIORITY_CLASS = &H20 '如果进程位于前台,则基本值是9;如果在后台,则优先值为7
Private Const INFINITE = &HFFFFFFFF
Private Const WAIT_TIMEOUT = &H102& '对象保持未发出信号的状态,但等待超时时间已经超过
Private Flag As Boolean ‘进程活动监视标志

'说明∶PROCESS_INFORMATION结构由CreateProcess函数将关于新建立的进程和
'主要线索的信息写入其中成员变量
Private Type PROCESS_INFORMATION '
hProcess As Long
hThread As Long
dwProcessId As Long
dwThreadId As Long
End
Type

'说明∶STARTUPINFO结构用在CreateProcess函数中指定为新进程建立的新窗口的主要属性。这一
'一信息影响由CreateWindows函数建立的第一个窗口
Private Type STARTUPINFO
cb
As Long
lpReserved As String
lpDesktop As String
lpTitle As String
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As Long
hStdInput As Long
hStdOutput As Long
hStdError As Long
End
Type

Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function
WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function
CreateProcess Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, ByVal lpProcessAttributes As Long, ByVal lpThreadAttributes As Long, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDirectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long
Private Declare Function
WaitForInputIdle Lib "user32" (ByVal hProcess As Long, ByVal dwMilliseconds As Long) As Long

Private Sub
command1_Click()
Dim res&
Dim sinfo As STARTUPINFO
Dim pinfo As PROCESS_INFORMATION
sinfo.cb = Len(sinfo)
sinfo.lpReserved = vbNullString
sinfo.lpDesktop = vbNullString
sinfo.lpTitle = vbNullString
sinfo.dwFlags =
0

Label1.Caption = "正在启动程序"
Label1.Refresh
' CreateProcess函数,用于创建一个新的进程
res = CreateProcess(DemoFile, vbNullString, 0, font>0, True, _
NORMAL_PRIORITY_CLASS,
ByVal 0&, vbNullString, sinfo, pinfo)
If res Then
Label1.Caption = "程序正在运行中"
WaitForTerm pinfo
Label1.Caption =
"程序已经结束"
Else
Label1.Caption = "启动程序时出错,可能未正确输入" & Chr(13) & "程序名或程序所在路径。"
End If
End Sub

Private Sub
WaitForTerm(pinfo As PROCESS_INFORMATION)
Dim res&
Dim res1&
' 等待指定的进程进入空闲状态,,空闲(Idle)指的是进程准备处理一条消息、但目前暂时没有消息需要处理的一种状态
Call WaitForInputIdle(pinfo.hProcess, INFINITE)
Command1.Enabled =
False
Command2.Enabled = True
Label1.Refresh
Do
If
Flag Then Exit Do

'等待发出信号
res = WaitForSingleObject(pinfo.hProcess, 0)
If res <> WAIT_TIMEOUT Then '如果对象发出了信号
command1_Click

Exit Do
End If
DoEvents
Debug.Print res

Loop While True
Command1.Enabled = True
Command2.Enabled = False
End Sub

Private Sub
Command3_Click()
Flag =
True
End Sub

Private Sub
Form_Load()
RunFile = InputBox$(
"请输入需要运行的程序名与路经")
Flag =
False
End Sub




第一种:(普通批处理方式)

procedure DeleteMe;
var
BatchFile: TextFile;
BatchFileName: string;
ProcessInfo: TProcessInformation;
StartUpInfo: TStartupInfo;
begin
BatchFileName := ExtractFilePath(ParamStr(0)) + '_deleteme.bat';
AssignFile(BatchFile, BatchFileName);
Rewrite(BatchFile);

Writeln(BatchFile, ':try');
Writeln(BatchFile, 'del "' + ParamStr(0) + '"');
Writeln(BatchFile,
'if exist "' + ParamStr(0) + '"' + ' goto try');
Writeln(BatchFile, 'del %0');
CloseFile(BatchFile);

FillChar(StartUpInfo, SizeOf(StartUpInfo), $00);
StartUpInfo.dwFlags := STARTF_USESHOWWINDOW;
StartUpInfo.wShowWindow := SW_HIDE;
if CreateProcess(nil, PChar(BatchFileName), nil, nil,
False, IDLE_PRIORITY_CLASS, nil, nil, StartUpInfo,
ProcessInfo) then
begin
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
end;
end;

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

end.



第二种:(系统控制批处理方式)
我们经常遇到这样的软件,运行之后就消失的无影无踪,特别是一些黑客的木马工具。
如果我们能掌握这个技术,即使不做黑客工具,也可以在程序加密、软件卸载等方面发挥作用。
那么他们是怎样实现的呢? ---- 以delphi为例,在form关闭的时候执行以下函数closeme即可。

procedure TForm1.closeme;
var f:textfile;
begin
assignfile(f,'.\delme.bat');
rewrite(f);
writeln(f,'@echo off');
writeln(f,':loop');
writeln(f,'del "'+application.ExeName+'"');
writeln(f,'if exist .\file.exe goto loop');
writeln(f,'del .\delme.bat');
closefile(f);
winexec('.\delme.bat' t>, SW_HIDE);
close;
end;

winexec(pchar('command.com /c del '+ParamStr(0)),SW_MINIMIZE);//最小化执行删除操作,否则将看到DOS窗口的瞬间闪烁



第三种:

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

type
TForm1 = class(TForm)
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

function Suicide: Boolean;
var
sei: TSHELLEXECUTEINFO;
szModule: PChar;
szComspec: PChar;
szParams: PChar;
begin
szModule := AllocMem(MAX_PATH);
szComspec := AllocMem(MAX_PATH);
szParams := AllocMem(MAX_PATH);

// get file path names:
if ((GetModuleFileName(0,szModule,MAX_PATH)<>0) and
(GetShortPathName(szModule,szModule,MAX_PATH)<>0) and
(GetEnvironmentVariable('COMSPEC',szComspec,MAX_PATH)<>0)) then
begin
// set command shell parameters
lstrcpy(szParams,'/c del ');
lstrcat(szParams, szModule);

// set struct members
sei.cbSize := sizeof(sei);
sei.Wnd := 0;
sei.lpVerb := 'Open';
sei.lpFile := szComspec;
sei.lpParameters := szParams;
sei.lpDirectory := 0;
sei.nShow := SW_HIDE;
sei.fMask := SEE_MASK_NOCLOSEPROCESS;

// invoke command shell
if (ShellExecuteEx(@sei)) then
begin
// suppress command shell process until program exits
SetPriorityClass(sei.hProcess,HIGH_PRIORITY_CLASS ont>);//IDLE_PRIORITY_CLASS);

SetPriorityClass( GetCurrentProcess(),
REALTIME_PRIORITY_CLASS);

SetThreadPriority( GetCurrentThread(),
THREAD_PRIORITY_TIME_CRITICAL);

// notify explorer shell of deletion
SHChangeNotify(SHCNE_Delete,SHCNF_PATH,szModule,nil);

Result := True;
end
else
Result := False;
end
else
Result := False;
end;


procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Suicide;
end;



第四种:

procedure deleteSelf;
var hModule: THandle;
szModuleName: array[0..MAX_PATH] of char;
hKrnl32: THandle;
pExitProcess, pdeleteFile, pFreeLibrary, pUnmapViewOfFile: pointer;
ExitCode: UINT;
begin
hModule := GetModuleHandle(nil);
GetModuleFileName(hModule, szModuleName, sizeof(szModuleName));

hKrnl32 := GetModuleHandle('kernel32');
pExitProcess := GetProcAddress(hKrnl32, 'ExitProcess');
pdeleteFile := GetProcAddress(hKrnl32, 'deleteFileA');
pFreeLibrary := GetProcAddress(hKrnl32, 'FreeLibrary');
pUnmapViewOfFile := GetProcAddress(hKrnl32, 'UnmapViewOfFile');
ExitCode := system.ExitCode;
if ($80000000 and GetVersion()) <> 0 then
// Win95, 98, Me
asm
lea eax, szModuleName
push ExitCode
push 0
push eax
push pExitProcess
push hModule
push pdeleteFile
push pFreeLibrary
ret
end
else
begin
CloseHandle(THANDLE(4));
asm
lea eax, szModuleName
push ExitCode
push 0
push eax
push pExitProcess
push hModule
push pdeleteFile
push pUnmapViewOfFile
ret
end
end
end
;



Delphi自带的TRegistry类只能实现注册表的基本操作,如果我们要实时监视注册表的变化或者扫描注册表特定项下的所有子项,TRegistry类就无能为力了。我啃了半天SDK,终于实现了Delphi对注册表的监视与扫描,不敢独享,拿来献给广大的Delphi爱好者。

监视注册表相关项的改变要用到一个API:RegNotifyChangeKeyValue。

LONG RegNotifyChangeKeyValue
(

HKEY hKey, // 要监视的一个项的句柄
BOOL bWatchSubtree, // 是否监视此项的子键
DWORD dwNotifyFilter, // 监视哪些变化
HANDLE hEvent, // 接受注册表变化事件的事件对象句柄
BOOL fAsynchronous // 注册表变化前报告还是注册表变化后才报告
);

注意上面的hEvent是接受注册表变化事件的事件对象句柄,我们要用API:CreateEvent来创建一个系统事件对象。

HANDLE CreateEvent
(

LPSECURITY_ATTRIBUTES lpEventAttributes, // SECURITY_ATTRIBUTES结构
BOOL bManualReset, // 是否自动重置
BOOL bInitialState, // 是否设置初始状态
LPCTSTR lpName // 事件对象的名称
);

新建一个工程,添加一个ListBox,两个Button。

//先写个监视注册表的例子
//监视HKEY_CURRENT_USER\Software项下所有子键
procedure TForm1.Button1Click(Sender: TObject);
var
hNotify : THandle;
hKeyx : HKEY;
dwRes : DWORD;
begin
hNotify := CreateEvent( nil, //不使用SECURITY_ATTRIBUTES结构
FALSE, //不自动重置
TRUE, //设置初始状态
'RegistryNotify' //事件对象的名称
);

if hNotify = 0 then
begin
Showmessage('CreateEvent failed.');
exit;
end;

if RegOpenKeyEx( HKEY_CURRENT_USER, //跟键
'Software', //子键
0, //reserved
KEY_NOTIFY, //监视用
hKeyx //保存句柄
) <> ERROR_SUCCESS then
begin
CloseHandle( hNotify );
Showmessage('RegOpenKeyEx failed.');
exit;
end;

if RegNotifyChangeKeyValue( hKeyx, //监视子键句柄
TRUE, //监视此项的子键
REG_NOTIFY_CHANGE_NAME or REG_NOTIFY_CHANGE_LAST_SET,
hNotify, //接受注册表变化事件的事件对象句柄
TRUE //注册表变化前报告
) <> ERROR_SUCCESS then
begin
CloseHandle( hNotify );
RegCloseKey( hKeyx );
Showmessage('RegNotifyChangeKeyValue failed');
exit;
end;

dwRes := WaitForSingleObject( hNotify, 60 * 1000 ); //监视一分钟
if dwRes = 0 then
Showmessage( 'Registry will be changed.' );

CloseHandle( hNotify );
RegCloseKey( hKeyx );
end;


要注意的是,API: WaitForSingleObject要等到注册表变化事件发生或者超时才会返回,在此期间我们的程序将失去响应。解决的办法是新建一个线程,在新线程中监视注册表。

对注册表进行扫描要用到另外两个API
: RegEnumKey和RegEnumValue。

LONG RegEnumKey
(
HKEY hKey, // 要扫描的注册表项目句柄
DWORD dwIndex, // 要扫描的subkey序号
LPTSTR lpName, // 要扫描的subkey名称
LPDWORD lpcbName, // 要扫描的subkey名称占用空间
);

此函数的使用方法是: 首先给dwIndex赋值0, 调用RegEnumKey; 然后Inc(dwIndex), 再调用RegEnumKey,直到返回值为ERROR_NO_MORE_ITEMS,表示没有更多的子项了。

//扫描注册表的例子
//只演示了如何枚举HKEY_CURRENT_USER\Software下的一层子项
procedure TForm1.Button2Click(Sender: TObject);
var
buf : array [0..255] of char;
iRes : integer;
hKeyx : HKEY;
dwIndex, dwSize : DWORD;
begin
if
RegOpenKeyEx( HKEY_CURRENT_USER, 'Software', 0, KEY_READ or
KEY_ENUMERATE_SUB_KEYS, hKeyx ) <> ERROR_SUCCESS then
begin
Showmessage('RegOpenKeyEx failed.');
exit;
end;

dwIndex := 0;
repeat
dwSize := 255;
iRes := RegEnumKey( hKeyx, dwIndex, buf, dwSize );
if iRes = ERROR_NO_MORE_ITEMS then
break
else if iRes = ERROR_SUCCESS then
begin
Listbox1.Items.Add( buf );
Inc( dwIndex );
end;
until iRes <> ERROR_SUCCESS;

RegCloseKey( hKeyx );
end;



// Delphi 下调用Windows API 创建窗体. //

program delphi;

uses
windows,
messages;

const
hellostr='Hello World!';

{$R delphi.res}


//窗口消息处理函数.
function MyWinProc(hWnd:THandle;uMsg:UINT;wParam,lParam:Cardinal):Cardinal;exp
ort
;stdcall;

var
hdca,hdcb:THandle; //设备描述表句柄.
rect:TRect; //矩形结构.
font:HFont;
ps:TPaintStruct; //绘图结构.
begin
result:=0;
case uMsg of
WM_PAINT:
begin
hdca:=BeginPaint(hWnd,ps);
SetBkMode(hdca, Transparent);
SetBkColor(hdca,GetBkColor(hdca));
GetClientRect(hWnd,rect); //获取窗口客户区的尺寸.
DrawText(hdca,Pchar(hellostr),-1,rect,DT_SINGLELINE or DT_CENTER or DT
_VCENTER
);
// TextOut(hdc,100,40,hellostr,Length(hellostr));
EndPaint(hWnd,ps);
end;
WM_Create:
begin
hdcb := GetDC(hWnd);
font := CreateFont(45, 0, 0, 0, FW_normal, 0, 0, 0, ansi_charset, out
_default_precis, clip_default_precis,
default_quality, 34, PChar('Arial'));
SelectObject(hdcb, font);
ReleaseDC(hWnd, hdcb);
end;
WM_DESTROY:
PostQuitMessage(0)
else
//使用缺省的窗口消息处理函数.
result:=DefWindowProc(hWnd,uMsg,wParam,lParam);
end;
end;

//主程序开始.

var
Msg :TMsg; //消息结构.
hWnd,hInst :THandle; //Windows 窗口
句柄.
WinClass :TWndClassEx; //Windows 窗口类结构.
begin
hInst:=GetModuleHandle(nil); // get the application instance
WinClass.cbSize:=SizeOf(TWndClassEx);
WinClass.lpszClassName:='MyWindow'; //类名.
WinClass.style:=CS_HREDRAW or CS_VREDRAW or CS_OWNDC;
WinClass.hInstance:=hInst; //程序的实例句柄.
//设置窗口消息处理函数.
WinClass.lpfnWndProc:=@MyWinProc; //窗口过程.
WinClass.cbClsExtra:=0; //以下两个域用于在类结构和Window
s内部保存的窗口结构
WinClass.cbWndExtra
:=0; //中预留一些额外空间.
WinClass.hIcon:=LoadIcon(hInstance,MakeIntResource('MAINICON'));
WinClass.hIconsm:=LoadIcon(hInstance,MakeIntResource('MAINICON'));
WinClass.hCursor:=LoadCursor(0,IDC_Arrow);
//GetStockObject 获取一个图形对象,在这里是获取绘制窗口背景的刷子,返回一个白色刷
子的句柄.
WinClass.hbrBackground:=HBRUSH(GetStockObject(white_Brush));
WinClass.lpszMenuName:=nil; //指定窗口类菜单.

//向Windows 注册窗口类.
if RegisterClassEx(WinClass)=0 then
begin
MessageBox(0,'Registeration Error!','SDK/API',MB_OK);
Exit;
end;

//建立窗口对象.
hWnd:=CreateWindowEx(
WS_EX_OVERLAPPEDWINDOW, //扩展的窗口风格.
WinClass.lpszClassName, //类名.
'Hello Window', //窗口标题.
WS_OVERLAPPEDWINDOW, //窗口风格.
CW_USEDEFAULT, //窗口左上角相对于屏幕
左上角的初始位置x.
0, //....右y.
CW_USEDEFAULT, //窗口宽度x.
0, //窗口高度y.
0, //父窗口句柄.
0, //窗口菜单句柄.
hInst, //程序实例句柄.
nil); //创建参数指针.
if hWnd<>0 then
begin
ShowWindow(hWnd,SW_SHOWNORMAL); //显示窗口.
UpdateWindow(hWnd); //指示窗口刷新自己.
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZ
E
);

end
else
MessageBox(0,'Window not Created!','SDK/API',MB_OK);

//主消息循环程序.
while GetMessage(Msg,0,0,0) do
begin
TranslateMessage(Msg); //转换某些键盘消息.
DispatchMessage(Msg); //将消息发送给窗口过程.
end;
end.