unit SysDriver;

interface

uses windows, winsvc; // jwawinsvc;

Type
TSysDriver = class(TObject)
private
HomeDir, DriverDir, DriverName, DEVICE_NAME_STRING,
DriverPath : string; // the whole thing
hSCMan : SC_HANDLE; // Service Control Manager
hDevice : SC_HANDLE; // Handle for device
public
HaveLoad : Boolean;
BaseControlCode : DWORD;
constructor Create(DeviceName: string); //---------------------------------------
// Interact with Service Control Manager
//---------------------------------------
function OpenSCM: DWORD;
function CloseSCM: DWORD; //---------------------------------------
// Install/Start/Stop/Remove driver
//---------------------------------------
function Install(newdriverpath: string): DWORD; { use '' for default }
function Start: DWORD;
function Stop: DWORD;
function Remove: DWORD; //--------------------------------
// Device Open/Close
//--------------------------------
function DeviceOpen: DWORD; // get a valid hDevice
function DeviceClose: DWORD; //--------------------------------
function IOControl(Cmd: DWORD; inBuf: Pointer; inSize: DWORD;
outbuf: Pointer; var outSize: DWORD): Boolean;
//--------------------------------
function ErrorLookup(ErrorNum: DWORD): string;
end; //-------------------------------------------
implementation
//-------------------------------------------
uses sysutils; Const // from ntddk
// Service Types (Bit Mask)
SERVICE_KERNEL_DRIVER = $;
SERVICE_FILE_SYSTEM_DRIVER = $;
SERVICE_ADAPTER = $;
SERVICE_RECOGNIZER_DRIVER = $; SERVICE_DRIVER = SERVICE_KERNEL_DRIVER or
SERVICE_FILE_SYSTEM_DRIVER or
SERVICE_RECOGNIZER_DRIVER; SERVICE_WIN32_OWN_PROCESS = $;
SERVICE_WIN32_SHARE_PROCESS = $;
SERVICE_WIN32 = SERVICE_WIN32_OWN_PROCESS or
SERVICE_WIN32_SHARE_PROCESS; SERVICE_INTERACTIVE_PROCESS = $; SERVICE_TYPE_ALL = SERVICE_WIN32 or
SERVICE_ADAPTER or
SERVICE_DRIVER or
SERVICE_INTERACTIVE_PROCESS;
// Start Type
SERVICE_BOOT_START = $;
SERVICE_SYSTEM_START = $;
SERVICE_AUTO_START = $;
SERVICE_DEMAND_START = $;
SERVICE_DISABLED = $; // Error control type
SERVICE_ERROR_IGNORE = $;
SERVICE_ERROR_NORMAL = $;
SERVICE_ERROR_SEVERE = $;
SERVICE_ERROR_CRITICAL = $; Type
TErrorMsg = record
Num: DWORD;
Msg: string;
end; Const
ErrorMsgCt = ;
ERROR_SCM_CANT_CONNECT = ;
ERROR_NO_DEVICE_HANDLE = ;
ERROR_GW_BUFFER_TOO_SMALL = ;
ERROR_UNEXPECTED = ; ErrorMsgs: array[..ErrorMsgCt] of TErrorMsg = (
(Num: ERROR_SUCCESS ; Msg: 'Operation was successful'),
(Num: ERROR_INVALID_FUNCTION ; Msg: 'Invalid Function'),
(Num: ERROR_ACCESS_DENIED ; Msg: 'Access denied'),
(Num: ERROR_CIRCULAR_DEPENDENCY ; Msg: 'Circular dependency'),
(Num: ERROR_DATABASE_DOES_NOT_EXIST ; Msg: 'Database doesn''t exist'),
(Num: ERROR_DEPENDENT_SERVICES_RUNNING; Msg: 'Dependent services running'),
(Num: ERROR_DUP_NAME ; Msg: 'Display name already exists'),
(Num: ERROR_INVALID_HANDLE ; Msg: 'Invalid handle'),
(Num: ERROR_INVALID_NAME ; Msg: 'Invalid service name'),
(Num: ERROR_INVALID_PARAMETER ; Msg: 'Invalid Parameter'),
(Num: ERROR_INVALID_SERVICE_ACCOUNT ; Msg: 'User account doesn''t exist'),
(Num: ERROR_INVALID_SERVICE_CONTROL ; Msg: 'Invalid service control code'),
(Num: ERROR_PATH_NOT_FOUND ; Msg: 'Path not found'),
(Num: ERROR_SERVICE_ALREADY_RUNNING ; Msg: 'Service already running'),
(Num: ERROR_SERVICE_CANNOT_ACCEPT_CTRL; Msg: 'Service can''t accept control'),
(Num: ERROR_SERVICE_DATABASE_LOCKED ; Msg: 'The database is locked'),
(Num: ERROR_SERVICE_DEPENDENCY_DeleteD; Msg: 'Depends on nonexistant service'),
(Num: ERROR_SERVICE_DEPENDENCY_FAIL ; Msg: 'Depends on service that failed'),
(Num: ERROR_SERVICE_DISABLED ; Msg: 'Service has been disabled'),
(Num: ERROR_SERVICE_DOES_NOT_EXIST ; Msg: 'Service doesn''t exist'),
(Num: ERROR_SERVICE_EXISTS ; Msg: 'Service already exists'),
(Num: ERROR_SERVICE_LOGON_FAILED ; Msg: 'Service couldn''t be logged on'),
(Num: ERROR_SERVICE_MARKED_FOR_Delete ; Msg: 'Service marked for deletion'),
(Num: ERROR_SERVICE_NO_THREAD ; Msg: 'Couldn''t create thread'),
(Num: ERROR_SERVICE_NOT_ACTIVE ; Msg: 'Service hasn''t been started'),
(Num: ERROR_SERVICE_REQUEST_TIMEOUT ; Msg: 'Service timed out'),
(Num: ERROR_GW_BUFFER_TOO_SMALL ; Msg: 'Buffer too small'),
(Num: ERROR_NO_DEVICE_HANDLE ; Msg: 'No device handle'),
(Num: ERROR_SCM_CANT_CONNECT ; Msg: 'Can''t connect to Service Control Manager'),
(Num: ERROR_UNEXPECTED ; Msg: 'An unexpected error occured')
); //-----------------------------------------
function TSysDriver.ErrorLookup(ErrorNum: DWORD): string;
//-----------------------------------------
Var
N: integer;
Begin
If Error <> ERROR_SUCCESS then
begin
result := 'Error: ' + IntToStr(ErrorNum) + ': ';
exit;
end; For N := to ErrorMsgCt do
Begin
if ErrorNum = ErrorMsgs[N].Num then
Begin
break;
end;
end;
result:=ErrorMsgs[N].Msg; end; //----------------------------------------------------------
// IOCTL codes
//----------------------------------------------------------
function CTL_CODE(DeviceType: integer; func: integer; meth: integer; access: integer): DWORD;
Begin
result := (DeviceType shl ) or (Access shl ) or (func shl ) or (meth);
end; Const
// Buffering method for user-mode app talking to drive
METHOD_BUFFERED = ;
METHOD_IN_DIRECT = ;
METHOD_OUT_DIRECT = ;
METHOD_NEITHER = ; // Define the access allowed
FILE_ANY_ACCESS = ;
FILE_READ_ACCESS = ; // file & pipe
FILE_WRITE_ACCESS = ; // file & pipe //-----------------------------------------
constructor TSysDriver.Create(DeviceName: string);
//-----------------------------------------
Begin
hSCMan := ;
hDevice := INVALID_HANDLE_VALUE;
HomeDir := ExtractFilePath(GetModuleName(HInstance));
DEVICE_NAME_STRING := DeviceName;
DriverName := DEVICE_NAME_STRING;
HaveLoad :=False;
// default driver name needed by stop/remove if install wasn't executed
// this run (ie: driver already installed
end; //-------------------------------------------
function TSysDriver.OpenSCM: DWORD;
//-------------------------------------------
Begin
result := ERROR_SUCCESS;
hSCMan := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if hSCMan = then result := ERROR_SCM_CANT_CONNECT;
end; //-------------------------------------------
function TSysDriver.CloseSCM: DWORD;
//-------------------------------------------
Begin
result := ERROR_SUCCESS;
CloseServiceHandle(hSCMan);
hSCMan := ;
end; //-----------------------------------------
function TSysDriver.Install(newdriverpath: string): DWORD; { use '' for default }
//-----------------------------------------
Var
hService: SC_HANDLE;
dwStatus: DWORD;
Begin
dwStatus := ; If newdriverpath = '' then
Begin
DriverDir := HomeDir;
DriverName := DEVICE_NAME_STRING;
end else
Begin
DriverDir := ExtractFilePath(newdriverpath);
// DriverName := ExtractFileName(driverpath);
end;
DriverPath := DriverDir + DriverName+'.sys'; // add to service control manager's database
hService := CreateService(hSCMan, PChar(DriverName),PChar(DriverName),
SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL, PChar(DriverPath),
nil, nil, nil, nil, nil);
if (hService = ) then
Begin
dwStatus := GetLastError();
end else
Begin
CloseServiceHandle(hService);
end; result := dwStatus;
end; //-------------------------------------------
function TSysDriver.Start: DWORD;
//-------------------------------------------
Var
hService: SC_HANDLE;
dwStatus: DWORD;
lpServiceArgVectors: PChar;
temp: LongBool;
Begin
dwStatus := ;
lpServiceArgVectors := nil; // get a handle to the service
hService := OpenService(hSCMan, PChar(DriverName), SERVICE_ALL_ACCESS);
if hService <> then
Begin
// start the driver
temp := StartService(hService, , PChar(lpServiceArgVectors));
if not temp then dwStatus := GetLastError();
end else dwStatus := GetLastError(); if (hService <> ) then CloseServiceHandle(hService);
result := dwStatus;
end; //-------------------------------------------
function TSysDriver.Stop: DWORD;
//-------------------------------------------
Var
hService: SC_HANDLE;
dwStatus: DWORD;
serviceStatus: TServiceStatus;
temp: LongBool;
Begin
dwStatus := ; // get a handle to the service
hService := OpenService(hSCMan, PChar(DriverName), SERVICE_ALL_ACCESS);
if hService <> then
Begin
// stop the driver
temp := ControlService(hService, SERVICE_CONTROL_STOP, serviceStatus);
if not temp then dwStatus := GetLastError();
end else dwStatus := GetLastError(); if (hService <> ) then CloseServiceHandle(hService);
result := dwStatus;
end; //-------------------------------------------
function TSysDriver.Remove: DWORD;
//-------------------------------------------
Var
hService: SC_HANDLE;
dwStatus: DWORD;
temp: LongBool;
Begin
dwStatus := Stop; // ignore result // get a handle to the service
hService := OpenService(hSCMan, PChar(DriverName), SERVICE_ALL_ACCESS);
if hService <> then
Begin
temp := DeleteService(hService);
if not temp then dwStatus := GetLastError();
end else dwStatus := GetLastError(); if (hService <> ) then CloseServiceHandle(hService);
result := dwStatus;
end; //=============================================================
// Device Open/Close functions
//============================================================= //-------------------------------------------
function TSysDriver.DeviceOpen: DWORD;
//-------------------------------------------
Var
dwStatus: DWORD;
Begin
dwStatus := ; if hDevice <> INVALID_HANDLE_VALUE then DeviceClose; // get a handle to the device
hDevice := CreateFile(
{ lpFileName: PChar } PChar('\\.\'+ DEVICE_NAME_STRING),
{ dwDesiredAccess: integer } GENERIC_READ or GENERIC_WRITE,
{ dwShareMode: Integer } ,
{ lpSecurityAttributes } nil,
{ dwCreationDisposition: DWORD } OPEN_EXISTING,
{ dwFlagsAndAttributes: DWORD } FILE_ATTRIBUTE_NORMAL,
{ hTemplateFile: THandle } ); if hDevice = INVALID_HANDLE_VALUE then
Begin
dwStatus := GetLastError();
end else
begin
HaveLoad:=True;
end; result := dwStatus;
end; //-------------------------------------------
function TSysDriver.DeviceClose: DWORD;
//-------------------------------------------
Var
dwStatus: DWORD;
Begin
dwStatus := ;
if (hDevice <> INVALID_HANDLE_VALUE) then CloseHandle(hDevice);
hDevice := INVALID_HANDLE_VALUE;
result := dwStatus; { assume that it went OK? }
end; //-------------------------------------------
function TSysDriver.IOControl(Cmd: DWORD; inBuf: Pointer; inSize: DWORD;
outbuf: Pointer; var outSize: DWORD): Boolean;
//-------------------------------------------
Var
BytesReturned: DWORD;
MyControlCode: DWORD; Begin
Result := False; if hDevice = INVALID_HANDLE_VALUE then Exit; MyControlCode := Cmd;//CTL_CODE(BaseControlCode, Cmd , METHOD_BUFFERED, FILE_ANY_ACCESS); BytesReturned := ;
Result := DeviceIoControl(hDevice, MyControlCode ,
{ in buffer (to driver) } InBuf, inSize,
{ out buffer (from driver) } OutBuf, outSize, BytesReturned, nil);
end; end.

http://www.lsworks.net/article/72.html

Delphi调用安装驱动sys的单元的更多相关文章

  1. CommMonitor8.0 串口过滤驱动 SDK DLL版本 C#/Delphi调用DEMO

    CommMonitor8.0 SDK DLL 版本,此版本是直接调用DLL. Delphi调用定义: constCommMOnitor8x = ‘CommMOnitor8x.dll’; typeTOn ...

  2. 用Setup系列函数完成驱动卸载安装[驱动安装卸载程序]

    // InstallWDFDriver.cpp : Defines the entry point for the console application. // #include "std ...

  3. 【转】Delphi调用webservice总结

    原文:http://www.cnblogs.com/zhangzhifeng/archive/2013/08/15/3259084.html Delphi调用C#写的webservice 用delph ...

  4. [转]Delphi调用cmd的两种方法

    delphi调用cmd的两种方法vars:string;begins:='cmd.exe /c '+edit1.Text+' >c:\1.txt';winexec(pchar(s),sw_hid ...

  5. Delphi调用webservice总结

    Delphi调用webservice总结     Delphi调用C#写的webservice 用delphi的THTTPRIO控件调用了c#写的webservice. 下面是我调试时遇到的一些问题: ...

  6. delphi调用外部程序打开文件

    delphi调用外部程序打开文件 ShellExecute的各种用法 一.利用系统默认的邮件收发器发送电子邮件 Uses ..., ShellAPI; Var lpHwnd: HWND; lpOper ...

  7. Delphi调用REST

    Delphi调用REST很简单,首先在界面上放上: RESTClient1: TRESTClient; RESTRequest1: TRESTRequest; RESTResponse1: TREST ...

  8. Delphi窗体创建释放过程及单元文件小结(转)

    Delphi窗体创建释放过程及单元文件小结 Delphi中的窗体,有模式窗体与非模式窗体两种.两种窗体的调用方式不同,模式窗体使用ShowModal显示,非模式窗体使用Show显示.当显示模式窗体的时 ...

  9. Delphi调用C++导出的QT类

    打开VS2008创建一个dll项目(创建了一个QT Library项目),新建头文件q4dapplication.h定义纯虚类: #ifndef Q4DAPPLICATION#define Q4DAP ...

随机推荐

  1. jQuery之Jcrop

    头像裁剪是一个经常用到的功能,实现原理也较为简单,就是在本地选择好所需裁剪图片的坐标,将坐标发送到服务器,由服务器执行图片裁剪操作. jQuery插件Jcrop提供了强大的图片裁剪坐标选择插件.一下来 ...

  2. EditText获取焦点监听事件_EditText获取和失去焦点操作

    今天在做搜索框的时候.遇到需要获取焦点之后做一些事情.实现方法也很简单.那就是绑定OnFocusChangeListener事件.实现 onFocusChange(View v, boolean ha ...

  3. Windows多线程同步系列之四-----信号量

    信号量说实话自己没怎么使用过.书上大概这样说,信号量设置一个资源访问计数.当该计数值大于0的时候,该信号量对象 为有信号状态,当该计数值等于0的时候,该信号量对象为无信号状态. 我们来查几个主要的AP ...

  4. java POI读取excel 2007/2003

    2003版office excel读取 import java.io.FileNotFoundException; import java.io.IOException; import java.io ...

  5. ALSA音频工具amixer,aplay,arecord

    ALSA音频工具编译安装 ========================================================================1.官网http://www. ...

  6. Linux 文件操作——系统调用和标准I/O库

    一.什么是文件 在讲述文件操作之前,我们首先要知道什么是文件.看到这个问题你可能会感觉到可笑,因为对于用过计算机的人来说,文件是最简单不过的概念了,例如一个文本是一个文件,一个work文档是一个文件等 ...

  7. PHP在Windows下安装配置第一步

    第一步就是下载和安装PHP解释器了: 1.下载Windows版本号的PHP解释器,下载地址:官方下载 我下载的是 VC11 x64 Thread Safe 这个以下的zip包 2.下载完毕后,解压到 ...

  8. 从一段代码看fork()函数及其引发的竞争

    首先来看一段从<UNIX环境高级编程>中摘录的一段很有意思的代码.借此我们再来谈谈fork()函数的一些问题. #include "apue.h" static voi ...

  9. 使用Xcode上传代码至GitHub

    几乎所有iOS程序员都上过GitHub寻找开源类库,的确,GitHub上有大量优秀的开源类库供大家学习.但是如何在Xcode中上传代码至GitHub呢? (开始之前先安装git,具体方法这里讲的很清楚 ...

  10. Android Native/Tombstone Crash Log 详细分析(转)

    转自:http://weibo.com/p/230418702c2db50102vc2h Android 虽然已经有好几年了,但是NDK的开放速度却非常缓慢,所以目前网络上针对对Android Nat ...