Search This Blog

Wednesday, December 24, 2008

MFC Code to get Process Name & Process ID and kill by process ID

#include "Tlhelp32.h"
#include "winbase.h"


// Function to kill Process using Process ID
int Killprocess(int nProcessID)
{
HANDLE hProcess = OpenProcess( PROCESS_TERMINATE, 0, nProcessID );
if (hProcess == NULL)
return -1;
BOOL nReturnVal = TerminateProcess( hProcess, 9 );
CloseHandle (hProcess);
return nReturnVal;
}


// Function to get all Process Name and Process ID
CString GetProcessNameandID()
{
HANDLE hSnapShot;
hSnapShot=CreateToolhelp32Snapshot (TH32CS_SNAPALL,NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize =sizeof(pEntry);
CString csProcessList;
DWORD dwID;
CString csProcessID;
//Get first process
Process32First (hSnapShot,&pEntry);
//Get all processes
while(1)
{
BOOL hRes=Process32Next (hSnapShot,&pEntry);
if(hRes==FALSE)
break;
csProcessList=csProcessList+pEntry.szExeFile;
dwID=pEntry.th32ProcessID;
csProcessID.Format("%i",dwID);
csProcessList=csProcessList +" "+csProcessID +"\r\n" ;
}
return csProcessList;
}

Friday, December 19, 2008

MFC code to Download a webPage

#include "afxinet.h" //add this header file

BOOL DownloadURL(const char *url, const char *filename, CString &errorMessage)
{
const int FILEBUFLEN = 1024;
char httpBuff[FILEBUFLEN];
TCHAR szErr[255];
errorMessage = "";

TRY {
CInternetSession session;
session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 1000);
session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 3);
CFile *remoteFile = session.OpenURL(url, 1 ,INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD);
CFile localFile(filename, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
int numBytes;
while (numBytes = remoteFile->Read(httpBuff, FILEBUFLEN))
{
localFile.Write(httpBuff, numBytes);
}
}
CATCH_ALL(error) {
error->GetErrorMessage(szErr,254,NULL);
errorMessage.Format("%s",szErr);
return FALSE;
}
END_CATCH_ALL;
return TRUE;
}

void CDownloadWebPageDlg::OnOK() //Copy the following Lines where you need to download.
{
CString csErr;
if(!DownloadURL("http://www.google.com","c:\\google.htm",csErr))
{
AfxMessageBox(csErr);
}
}

Hide the Taskbar application button

Open the .rc file in notepad
search for the line

"EXSTYLE WS_EX_APPWINDOW "

and replace "WS_EX_APPWINDOW" with "WS_EX_TOOLWINDOW".

Save and Close

MFC Code to avoid a Application running Many times

Paste this following code in BOOL CYourProjectNameApp::InitInstance() function of you Aplliction.


CreateMutex(NULL,TRUE,"Sample");
// mutex will be automatically deleted when process ends.
BOOL bAlreadyRunning = (GetLastError() == ERROR_ALREADY_EXISTS);
if(bAlreadyRunning)
{
::MessageBox(NULL, "This Appliction is Already Running ", "Information",
MB_ICONINFORMATION|MB_OK|MB_DEFBUTTON1);
return 0;
}

Thursday, December 18, 2008

MFC Code to Close Task manager Automatically if it is lanched

BOOL g_bStopDialogWatcherThread = FALSE; // To Stop & start Thread

UINT DialogWatcher(LPVOID lpParam)
{
g_bStopDialogWatcherThread = FALSE;
while(1)
{
Sleep(300);
HWND hWnd = ::FindWindow(NULL,"Windows Task Manager");//Windows Task Manager


if(hWnd !=NULL)
{
// ::SetForegroundWindow(hWnd);
// ::SetFocus(hWnd);
// ::SetWindowPos(hWnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE );
// ::SendMessage(hWnd,WM_COMMAND,(WPARAM)0x0000025C,(LPARAM)0x0000025C);

::SendMessage(hWnd,WM_CLOSE,0,0);

}

if(g_bStopDialogWatcherThread)
{
break;
}
}
return 1;
}




void CFindWindowDlg::OnbtnClick()
{
AfxBeginThread(DialogWatcher,THREAD_PRIORITY_NORMAL,0,0,0);

}

void CFindWindowDlg::OnCancel()
{
g_bStopDialogWatcherThread = TRUE;
CDialog::OnCancel();
}

Thursday, December 11, 2008

UnManaged and Managed (CLR) Data Type equivalants

Unmanaged Windows API types Unmanaged C language types CLR type
HANDLE void* IntPtr
BYTE unsigned char Byte
SHORT short Int16
WORD unsigned short UInt16
INT, LONG int, long Int32
BOOL int, long Int32 or Boolean
UINT unsigned int UInt32
DWORD, ULONG unsigned long UInt32
CHAR char Char
LPSTR, LPCSTR, LPWSTR, LPCWSTR char*, wchar_t* String or StringBuilder
FLOAT float Single
DOUBLE double Double

Wednesday, December 10, 2008

Calling DLL with wrapper from Application exe

  1. Create a MFC Appwizard(exe) the project name "TestDLL"
  2. Using the wizard select dialog based application.
  3. Add three "Edit Box" and add member name as m_edA, m_edB and m_edResult and choose Category as variable and Type as int.
  4. Add a new class with class name "CWrapper" with class type "Generic Class".
  5. Add a new header file with name "MyAPI.H".
  6. Edit the following files as the instruction given below.
  7. copy the "MyDll.dll" DLL created earlier and paste it where your exe application created. By default in "Debug" folder of your Project.

// Add the following lines in MyAPI.H
#define DLLNAME "MyDLL.dll"
//function pointers for Exportable API's
typedef int (*egAddFn) (int A, int B);


// Add the following lines in TestDLLDlg.h
#include "Wrapper.h"
class CTestDLLDlg : public CDialog
{
private:
CWrapper m_Wrapper; //add this line
};


//Add the following lines in Wrapper.h
#include "MyAPI.h"
class CWrapper
{
public:
OnInitialize(); //add this line
OnUnInitialize(); //add this line
HINSTANCE m_hInstance; //add this line
int egAdd(int a,int b); //add this line
egAddFn m_egAddFn; //add this line
};


//Add the following lines in TestDLLDlg.cpp
void CTestDLLDlg::OnBtnAdd()
{
UpdateData(TRUE);
int a=0,b=0,c=0;
a=m_edA; //name of the edit box with type int
b=m_edB; //name of the edit box with type int
if(m_Wrapper.m_egAddFn)
{
c=m_Wrapper.m_egAddFn(a,b);
}
m_edResult=c; //name of the edit box with type int
UpdateData(FALSE);
}


//Add the following lines in Wrapper.cpp:
#include "Wrapper.h"
CWrapper::CWrapper()
{
m_hInstance = NULL;
//Initialize all function pointers to NULL
m_egAddFn = NULL;
OnInitialize();
}

CWrapper::~CWrapper()
{
OnUnInitialize();
}

int CWrapper::OnInitialize()
{
CString csDllPath,csLeft;
TCHAR szPath[MAX_PATH];
int nPos;
szPath[0] = NULL;
GetModuleFileName(NULL,szPath,MAX_PATH);
csDllPath = szPath;
nPos = csDllPath.ReverseFind ('\\');
if(nPos != -1)
{
csLeft = csDllPath.Left (nPos);
csDllPath.Format ("%s\\%s",csLeft,DLLNAME);
}
else
{
csDllPath = DLLNAME;
}
m_hInstance = LoadLibrary(csDllPath);
if(m_hInstance)
{
m_egAddFn = (egAddFn) GetProcAddress (m_hInstance, "egAdd");
}
else
{
m_egAddFn = NULL;
return 0;
}
return 1;
}
int CWrapper::OnUnInitialize()
{
if(m_hInstance)
{
FreeLibrary(m_hInstance);
}
else
{
m_hInstance = NULL;
//Initialize all function pointers to NULL

m_egAddFn=NULL;
return 0;
}
return 1;
}

int CWrapper::egAdd(int a ,int b)
{
if (m_egAddFn)
{
return m_egAddFn (a,b);
}
return 0;
}

MFC DLL with wrapper

  1. Create a MFC DLL with the project name "MyDLL"
  2. Add a new class with class name "CMyClass" with class type "Generic Class".
  3. Edit the following files as the instruction given below.

// Add the following lines in MyClass.h
class CMyClass
{
public:
int Add(int a , int b); //add this Line
};


// Add the following lines in MyDLL.h
#include "MyClass.h"
#ifndef EXP
#define EXP extern "C" __declspec( dllexport )
#endif
#define APPPTR ((CMyDLLApp*) AfxGetApp())
class CMyDLLApp : public CWinApp
{
public:
CMyClass m_MyObj; //add this line
};


// Add the following lines in MyClass.cpp:
#include "stdafx.h"
#include "MyDLL.h"
#include "MyClass.h"
int CMyClass::Add(int a , int b)
{
return(a+b);
}



// Add the following lines in MyDLL.cpp
#include "stdafx.h"
#include "MyDLL.h"
#include "MyClass.h"

EXP int egAdd(int a, int b)
{
int c=0;
c= APPPTR->m_MyObj.Add(a,b);
return c;
}