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;
}

Saturday, November 22, 2008

An Example to call MFC DLL using function pointer in C#.net

//An Example to call MFC DLL using function pointer in C#.net
  1. Create new C#.Net windows application.
  2. Copy the "MyDll.dll" to your project path, which we created in this post Click here.
  3. Create two Textbox textBox1 and textBox2.

using System.Runtime.InteropServices; //Add this Line

namespace WindowsApplication1
{
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
//Add the Following Lines
IntPtr MyDll = LoadLibrary("MyDll.dll");
IntPtr procaddr = GetProcAddress(MyDll, "egAdd");
MyAdd mAdd = (MyAdd)Marshal.GetDelegateForFunctionPointer(procaddr, typeof(MyAdd));
int a = Convert.ToInt32(textBox1.Text);
int b = Convert.ToInt32(textBox2.Text);
int nRes = mAdd(a, b);
MessageBox.Show(nRes.ToString());
}
internal delegate int MyAdd(int a,int b);
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(String dllname);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule, String procname);
}
}

C#.Net code to call MFC DLL

This is the code to call a function from vc++ DLL
(for example "MyDll.dll" which we created in this post click here )
  1. Create a new C#.net windows application.
  2. Copy the "MyDll.dll" to your project path, which we created in this post Click here.
  3. Add this this following lines as below.
//using System.Runtime.InteropServices is used to call dll function in C#
using System.Runtime.InteropServices; //add this line

namespace WindowsApplication1
{
public partial class Form1 : Form
{

[DllImport("MyDll.dll", CharSet=CharSet.Auto)] //add this line
internal static extern Int32 egAdd(int a, int b); //add this line

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
int nRes = egAdd(2, 4); //add this line
MessageBox.Show(nRes.ToString()); //add this line
}

}
}

Saturday, November 8, 2008

How to create MFC DLL without wrapper class

Steps to create DLL
  • Select File--> New
  • Select Projects TAB and select MFC AppWizard(dll)
  • Give Project Name as "MyDLL".
  • Select "Regular DLL with MFC statically Linked" and click Finish.
  • Select "Insert" Menu and choose "New Class".
  • Select class type as "Generic Class"
  • Give class name as "MyClass".
  • Open "MyClass.h" in solution explorer window of File View tab.
  • Paste the following code as in Figure 1.
  • class CMyClass
    {
    public:
    __declspec(dllexport) CString Hello(CString csName);
    __declspec(dllexport) CMyClass();
    __declspec(dllexport) virtual ~CMyClass();

    };
  • Open "MyClass.cpp" in solution explorer window of File View tab.
  • Paste the following code as in Figure 2.
  • CString CMyClass::Hello(CString csName)
    {

    csName="Hello"+csName;

    return csName;
    }
  • Now compile and run the program.
  • Now Make a copy "MyClass.h" from you project folder and Copy of "MyDLL.lib" and "MyDLL.dll" from debug folder to create a exe file.
Steps to create EXE apllcation
  • Select File--> New
  • Select Projects TAB and select MFC AppWizard(exe).
  • Give Project Name as "MyEXE".
  • Select "Dialog Based" and click Finish.
  • paste "MyClass.h" from dll project folder to your exe Project folder.
  • Paste "MyDLL.lib" and "MyDLL.dll" from debug of DLL project folder to exe project Folder.
  • Open Project -->settings and select Link tab and type "Debug/MyDll.lib" in object/Library modules
  • Open " File View" tab in solution explorer window.
  • Right click on the project name and select add files to project.
  • select "MyClass.h" and click ok.
  • Now Open " Resource View" tab in solution explorer window and select Dialog and open "IDD_MYEXE_DIALOG".
  • Now add a "Edit Box" to your dialog window and Right click on edit box and select "Class Wizard" .
  • select "member variable" tab and select your edit box and click "Add variable " button.
  • Give member variable name as "m_edName" and category as Control.
  • Now click "ok" button and add the following code in "MyEXEDlg.cpp" as in Figure 3.
  • #include "myclass.h" //at the top
  • void CMyEXEDlg::OnOK()
    {
    CString csName;
    CString csResult;
    m_edName.GetWindowText(csName);
    CMyClass obj;
    csResult= obj.Hello(csName);
    AfxMessageBox(csResult);
    // CDialog::OnOK();
    }
  • Now Run and execute program. and get result as in figure 4.