Міністерство освіти України
Національний університет „Львівська політехніка”
Кафедра ПЗК
Курсова робота:
„ООП та створення потоків у середовищі MS Windows”
Зміст
Зміст 2
Теоретичні відомості 3
Текст програми 5
another.cpp 5
another.h 5
proc.cpp 6
proc.h 10
procview.cpp 12
Протокол роботи програми 14
Теоретичні відомості
Для роботи з процесами використовується бібліотека Toolhelp32 яка лістить ряд функції які дозволяються працювати з системою на рівні ядра.
Для її ініціалізвції необхідно спочатку підключити динамічну біліотеку KERNEL32.DLL, викликати фукцію ініціалізації бібіліотеки HANDLE WINAPI reateToolhelp32Snapshot(DWORD dwFlags, DWORD th32ProcessID). Далі необхідно здійснити отримання вказівників на фукції які забезпечують безпосереднє отримання даних про процес:
pModule32First = (MODULEWALK)GetProcAddress(hKernel,"Module32First");
pModule32Next = (MODULEWALK)GetProcAddress(hKernel,"Module32Next");
pProcess32First = (PROCESSWALK)GetProcAddress(hKernel,"Process32First");
pProcess32Next = (PROCESSWALK)GetProcAddress(hKernel,"Process32Next");
pThread32First = (THREADWALK)GetProcAddress(hKernel,"Thread32First");
pThread32Next = (THREADWALK)GetProcAddress(hKernel,"Thread32Next");
Оскільки система недозволяє безпосередньо втручатися в адресний простір ядра і самих процесів, то необхідно виконати “фотографування” пам’яті системи з метою отримання “знімку” який дасть можливість їх переглянути.
hThreadSnap = pCreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
Далі організовуємо цикл в якому задопомогою фукції Thread32First і Thread32Next продимо перегляд отриманого “знімку”.
if (pThread32First(hThreadSnap, &te32)) {
do {
if (te32.th32OwnerProcessID == dwOwnerPID) {
TThreadINFO *ti=new TThreadINFO;
ti->cntUsage = te32.cntUsage;
ti->ThreadID = te32.th32ThreadID;
ti->OwnerProcessID = te32.th32OwnerProcessID;
ti->DeltaPri = te32.tpDeltaPri;
ti->BasePri = te32.tpBasePri;
ti->Flags = te32.dwFlags;
AddThreadItem(ti,Treads);
}
}
while (pThread32Next(hThreadSnap, &te32));
bRet = TRUE;
}
else bRet = FALSE;
Для зміни пріоретету професу необхідно отримати його ID (HANDLE hThread) і задавши його бажаний пріоритет використовуючи фукцію
BOOL SetThreadPriority(
HANDLE hThread, // handle to the thread
int nPriority // thread priority level
);
його встановити. Можливі варіанти приоритету:
THREAD_PRIORITY_ABOVE_NORMAL – зижче нормального
THREAD_PRIORITY_BELOW_NORMAL – вижче нормального
THREAD_PRIORITY_HIGHEST - найвищий
THREAD_PRIORITY_IDLE - найнижщий
THREAD_PRIORITY_LOWEST - низький
THREAD_PRIORITY_NORMAL – нормальний (задається потоку при його створенні по замовчуванню)
THREAD_PRIORITY_TIME_CRITICAL – критичний до часу
Текст програми
another.cpp
//----------------------------------------------------------------------------
//Borland C++Builder
//Copyright (c) 1987, 1998 Borland International Inc. All Rights Reserved.
//----------------------------------------------------------------------------
//---------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "another.h"
//TShiftState st;
//---------------------------------------------------------------------
#pragma resource "*.dfm"
TForm2 *Form2;
//---------------------------------------------------------------------
__fastcall TForm2::TForm2(TComponent *Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------
another.h
//----------------------------------------------------------------------------
//Borland C++Builder
//Copyright (c) 1987, 1998 Borland International Inc. All Rights Reserved.
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
#ifndef AnotherH
#define AnotherH
//----------------------------------------------------------------------------
#include <ExtCtrls.hpp>
#include <StdCtrls.hpp>
#include <Dialogs.hpp>
#include <Forms.hpp>
#include <Controls.hpp>
#include <Graphics.hpp>
#include <Classes.hpp>
#include <SysUtils.hpp>
#include <Messages.hpp>
#include <Windows.hpp>
#include <System.hpp>
//----------------------------------------------------------------------------
class TForm2 : public TForm
{
__published:
TButton *Button1;
TLabel *Title;
TLabel *Comments;
TLabel *Copyright;
TLabel *Borland;
public:
virtual __fastcall TForm2(TComponent *Owner);
};
//----------------------------------------------------------------------------
extern TForm2 *Form2;
//----------------------------------------------------------------------------
#endif
proc.cpp
//----------------------------------------------------------------------------
//Borland C++Builder
//Copyright (c) 1987, 1998 Borland International Inc. All Rights Reserved.
//----------------------------------------------------------------------------
//---------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <stdlib.h>
#include "proc.h"
#include "another.h"
//---------------------------------------------------------------------
#pragma resource "*.dfm"
#pragma resource "procv2.res"
TFormMain *FormMain;
//---------------------------------------------------------------------
static int stat=1;
int i=0;
//---------------------------------------------------------------------
__fastcall TFormMain::TFormMain(TComponent *Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------
bool __stdcall EnumProc(HWND hWnd,/*LPARAM*/long/*lp*/)
{
unsigned long* pPid; //LPDWORD
unsigned long result; //DWORD
void *hg; //HGLOBAL
unsigned long id;
if(hWnd==NULL)
return false;
hg = GlobalAlloc(GMEM_SHARE,sizeof(unsigned long));
pPid = (unsigned long *)GlobalLock(hg);
result = GetWindowThreadProcessId(hWnd,pPid);
if(result){
char title[110];
char className[95];
char totalStr[256];
GetClassName(hWnd,className,95);
GetWindowText(hWnd,title,110);
id=*pPid;
ultoa(id,totalStr,10);
strcat(totalStr,"\t");
if(title){
strcat(totalStr,title);
strcat(totalStr,"\t");
}
strcat(totalStr,className);
FormMain->ListBox1->Items->Add((AnsiString)totalStr);
}
else{
GlobalUnlock(hg);
GlobalFree(hg);
return false;
}
GlobalUnlock(hg);
GlobalFree(hg);
return true;
}
//---------------------------------------------------------------------
void __fastcall TFormMain::Exit1Click(TObject* /*Sender*/)
{
PostQuitMessage(0);
}
//----------------------------------------------------------------------------
void __fastcall TFormMain::About1Click(TObject* /*Sender*/)
{
Form2->ShowModal();
}
//----------------------------------------------------------------------------
void __fastcall TFormMain::SpeedButton4Click(TObject* /*Sender*/)
{
long lp=0;
ListBox1->Enabled=true;
ListBox1->Clear();
EnumWindows((WNDENUMPROC)EnumProc,lp);
SpeedButton2->Enabled=true;
SpeedButton3->Enabled=true;
}
//----------------------------------------------------------------------------
void __fastcall TFormMain::RadioButton1Click(TObject* Sender)
{
TRadioButton *rbp =(TRadioButton*) Sender;
ListBox1->Font->Color=rbp->Font->Color;
}
//----------------------------------------------------------------------------
void __fastcall TFormMain::New1Click(TObject* /*Sender*/)
{
SpeedButton4Click(0);
}
//----------------------------------------------------------------------------
void __fastcall TFormMain::Refresh1Click(TObject* /*Sender*/)
{
SpeedButton4Click(0);
}
//----------------------------------------------------------------------------
void __fastcall TFormMain::SpeedButton3Click(TObject* /*Sender*/)
{
ListBox1->Clear();
SpeedButton3->Enabled=false;
SpeedButton1->Enabled=false;
}
//----------------------------------------------------------------------------
void __fastcall TFormMain::ListBox1Click(TObject* /*Sender*/)
{
SpeedButton1->Enabled=true;
StatusBar1->SimpleText="Select 'Kill Selected PID' to terminate the process";
}
//----------------------------------------------------------------------------
void __fastcall TFormMain::FormShow(TObject */*Sender*/)
{
if(stat){
stat= 0;
ListBox1->Items->Add((AnsiString)"Click on 'pid' Tool button above");
}
}
//---------------------------------------------------------------------
void __fastcall TFormMain::Timer1Timer(TObject */*Sender*/)
{
switch(i){
case 0:{
Image1->Picture->Bitmap->LoadFromResourceName(0,(AnsiString)"BITMAP_5");
Image1->Refresh();
i=1;
return;
}
case 1:{
Image1->Picture->Bitmap->LoadFromResourceName(0,(AnsiString)"BITMAP_2");
Image1->Refresh();
i=2;
return;
}
case 2:{
Image1->Picture->Bitmap->LoadFromResourceName(0,(AnsiString)"BITMAP_3");
Image1->Refresh();
i=3;
return;
}
case 3:{
Image1->Picture->Bitmap->LoadFromResourceName(0,(AnsiString)"BITMAP_4");
Image1->Refresh();
i=4;
return;
}
case 4:{
Image1->Picture->Bitmap->LoadFromResourceName(0,(AnsiString)"BITMAP_1");
Image1->Refresh();
i=0;
return;
}
}//end switch
}
void __fastcall TFormMain::SpeedButton2Click(TObject *Sender)
{
SpeedButton4Click(0);
SpeedButton1->Enabled=false;
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::SpeedButton1Click(TObject *Sender)
{
try {
AnsiString str;
char *tmp;
int i;
i= ListBox1->ItemIndex;
if( i != -1){
AnsiString s;
tmp = new char[100];
s=ListBox1->Items->Strings[i];
strcpy(tmp,(char*)s.c_str());
tmp=strtok(tmp,"\t");
}
int id=atoi(tmp);
delete[] tmp;
HANDLE ps = OpenProcess(1,false,id);
if(ps){
if(!TerminateProcess(ps,-9)){
ShowMessage((AnsiString)"Could not end process specified!");
}
else{
ShowMessage((AnsiString)"Process successfully terminated!");
}
}
else{
ShowMessage((AnsiString)"Could not open process requested!");
}
}
catch(Exception &e)
{
ShowMessage("Please select a PID");
}
}
//---------------------------------------------------------------------------
proc.h
//----------------------------------------------------------------------------
//Borland C++Builder
//Copyright (c) 1987, 1998 Borland International Inc. All Rights Reserved.
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
#ifndef ProcH
#define ProcH
//----------------------------------------------------------------------------
#include <ComCtrls.hpp>
#include <Buttons.hpp>
#include <ExtCtrls.hpp>
#include <Menus.hpp>
#include <StdCtrls.hpp>
#include <Dialogs.hpp>
#include <Forms.hpp>
#include <Controls.hpp>
#include <Graphics.hpp>
#include <Classes.hpp>
#include <SysUtils.hpp>
#include <Messages.hpp>
#include <Windows.hpp>
#include <System.hpp>
//----------------------------------------------------------------------------
class TFormMain : public TForm
{
__published:
TGroupBox *GroupBox1;
TRadioButton *RadioButton1;
TRadioButton *RadioButton2;
TRadioButton *RadioButton3;
TMainMenu *MainMenu1;
TMenuItem *File1;
TMenuItem *New1;
TMenuItem *Exit1;
TMenuItem *N1;
TMenuItem *Help1;
TMenuItem *About1;
TPanel *Panel1;
TSpeedButton *SpeedButton3;
TSpeedButton *SpeedButton4;
TStatusBar *StatusBar1;
TListBox *ListBox1;
TMenuItem *Refresh1;
TRadioButton *RadioButton4;
TLabel *Label2;
TLabel *Label3;
TLabel *Label4;
TTimer *Timer1;
TImage *Image1;
TBevel *Bevel1;
TSpeedButton *SpeedButton2;
TSpeedButton *SpeedButton1;
void __fastcall Exit1Click(TObject *Sender);
void __fastcall About1Click(TObject *Sender);
void __fastcall SpeedButton4Click(TObject *Sender);
void __fastcall RadioButton1Click(TObject *Sender);
void __fastcall New1Click(TObject *Sender);
void __fastcall Refresh1Click(TObject *Sender);
void __fastcall SpeedButton3Click(TObject *Sender);
void __fastcall ListBox1Click(TObject *Sender);
void __fastcall FormShow(TObject *Sender);
void __fastcall Timer1Timer(TObject *Sender);
void __fastcall SpeedButton2Click(TObject *Sender);
void __fastcall SpeedButton1Click(TObject *Sender);
public:
virtual __fastcall TFormMain(TComponent *Owner);
};
//----------------------------------------------------------------------------
extern TFormMain *FormMain;
//----------------------------------------------------------------------------
#endif
procview.cpp
//----------------------------------------------------------------------------
//Borland C++Builder
//Copyright (c) 1987, 1998 Borland International Inc. All Rights Reserved.
//----------------------------------------------------------------------------
//---------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
//---------------------------------------------------------------------
USEFILE("readme.txt");
USEFORM("proc.cpp", FormMain);
USEFORM("another.cpp", Form2);
USERES("Procview.res");
//---------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
Application->Initialize();
Application->CreateForm(__classid(TFormMain), &FormMain);
Application->CreateForm(__classid(TForm2), &Form2);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
return 0;
}
//---------------------------------------------------------------------
Протокол роботи програми