Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

[Tips] Using C++ to Inject a DLL with C# Source Code

Wednesday 6 January 2016
|
Read: Completed in minutes

[Tips] Using C++ to Inject a DLL with C# Source Code

Inject DLL with C++ is one of hot topic for software developers. Use inject Dll tech skill you can doing much application


Injects DLL C++ use C# source code


Description:
Case 1:
- I have two application (all my build) A and B, I can SendMessage from application A to B
- Application B will be received and can process as my mine

Case 2:
- I have two application: A  (is my build) and B (is the third application). If I SendMessage from Application A to B and control B, I can't do it, because B is not my application. So I MUST using another dll and injects it to B, After then I can control it. :). Below I'll introduce to you How to inject to application B and control it!





The list software using inject dll or hook:
1. UniKey software (Help you type Vietnamese language.)
2. AutoPlay
3. ...

C# Source Code
/* Developer: Zidane (huuvi168@gmail.com)
 * last Modified: 2013-12-23
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace AutoPlay
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        { 
            InitializeComponent();
        }

       
        private void btnSend_Click(object sender, EventArgs e)
        {            
            IntPtr hwnd = clsWin32.FindWindow("FSOnline Class", null);

            if (hwnd != null)
            {
                string message = txtMsg.Text + "-" + System.DateTime.Now.ToString();
                clsWin32.COPYDATASTRUCT cds;
                cds.dwData = clsAutoPlayer.DATA_LOCKSOMEONEUSESKILL;
                cds.lpData = (int)Marshal.StringToHGlobalAnsi(message);
                cds.cbData = message.Length;
                clsWin32.SendMessage(hwnd, (int)clsWin32.WM_COPYDATA, 0, ref cds);                                
                clsWin32.SendMessage(hwnd, (int)clsWin32.WM_HOOK_WRITE, clsAutoPlayer.WPARAM_FUNCTION1, 180);
            }
            else
                MessageBox.Show("Cannot find Windows");
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            
        }

        private void btnSend2_Click(object sender, EventArgs e)
        {
            IntPtr hwnd = clsWin32.FindWindow("FSOnline Class", null);

            if (hwnd != null)
                clsWin32.SendMessage(hwnd, (int)clsWin32.WM_HOOK_WRITE, clsAutoPlayer.WPARAM_FUNCTION2, 380);
            else
                MessageBox.Show("Cannot find Windows");
        }

        private void btnInject_Click(object sender, EventArgs e)
        {
            IntPtr hwnd = clsWin32.FindWindow("FSOnline Class", null);

            if (hwnd != null)
                clsWin32.InjectDll(hwnd);

            else
                MessageBox.Show("Cannot find Windows");
        }
    }
}


/// ***************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AutoPlay
{
    class clsAutoPlayer
    { 
        public const int DATA_LOCKSOMEONEUSESKILL = 0;
        public const int WPARAM_FUNCTION1 = 1001;
        public const int WPARAM_FUNCTION2 = 1002;

    }
}


/// ***************************************************************************

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace AutoPlay
{
    public class clsWin32
    {
        public const int WM_COPYDATA = 0x4A;
        public const int WM_HOOK_WRITE = 20000;

        [StructLayout(LayoutKind.Sequential)]
        public struct COPYDATASTRUCT
        {
            public int dwData;
            public int cbData;
            public int lpData;
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, ref COPYDATASTRUCT lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);


        [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);


        // my dll
        [DllImport("..\\..\\lib\\NativeDLL.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int InjectDll(IntPtr hwnd);

        //[DllImport("NativeDLL.dll", CallingConvention = CallingConvention.Cdecl)]

        [DllImport("..\\..\\lib\\Release\\NativeDLL.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int UnmapDll(IntPtr hWnd);

    }
}





C++ Source Code

/* Developer: Zidane (huuvi168@gmail.com)
 * last Modified: 2013-12-23
 */

// dllmain.cpp : Defines the entry point for the DLL application.

#include "stdafx.h"
#include "Controller.h"
#include <iostream>
#include <stdio.h>

// ------- Define -------

#define DATA_LOCKSOMEONEUSESKILL 0

#define WM_HOOK_WRITE    20000
#define WPARAM_FUNCTION1 1001
#define WPARAM_FUNCTION2 1002

// -------- Structures
bool bUseMouse;

typedef struct struct_function1
{ 
 int iIndex;   // skill ID
 int iPos;   // vị trí monster trong mảng NPC
}MYFUNCTION1;   // struct tham số cho function MYFUNCTION1 

// ---------- Load dll
using namespace std;



// ---------- Main Function

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
      )
{

 AllocConsole(); 
 freopen("CONOUT$", "w", stdout);  

 switch (ul_reason_for_call)
 {
 case DLL_PROCESS_ATTACH:
  hModuleDll = (HINSTANCE) hModule;
  
  std::cout << "Inject successfully!" << std::endl;

  DisableThreadLibraryCalls(hModuleDll);
  break;

 case DLL_THREAD_ATTACH:
  cout << "Inject DLL_THREAD_ATTACH!" << endl;
  break;


 case DLL_THREAD_DETACH:
  cout << "Inject DLL_THREAD_DETACH!" << endl;
  break;

 case DLL_PROCESS_DETACH:
  cout << "Inject DLL_PROCESS_DETACH!" << endl;
  break;
 }

 return TRUE;
}

LRESULT _stdcall CALLBACK HookProc (int nCode, WPARAM wParam, LPARAM lParam)
{
 
 if(nCode<0)
  goto END;
 
 HWND hVLWnd = pCW->hwnd; 
 
 if (pCW->lParam == MSG_LBUTTONDOWN) // button down
 {
  bUseMouse = TRUE;
  //g_logWriter.WriteLog(LOG_TYPE_DEBUG, L"Mouse Down");
 }

 else if (pCW->lParam == MSG_LBUTTONUP) // button up
 {
  bUseMouse = FALSE;
  //g_logWriter.WriteLog(LOG_TYPE_DEBUG, L"Mouse up");
 }

 if((pCW->message == WM_HOOKEX) && pCW->lParam)
 {  
  UnhookWindowsHookEx(hHook);
  if (bHooked)
   goto END;
  TCHAR lib_name[MAX_PATH];
  GetModuleFileName(hModuleDll, lib_name, MAX_PATH);
  if(!LoadLibrary(lib_name))
   goto END;
  OldWndProc = (WNDPROC)SetWindowLong(hVLWnd, GWL_WNDPROC, (LONG)NewWndProc);
  if(OldWndProc==NULL) {
   FreeLibrary(hModuleDll);
  }
  else
  {
   bHooked = TRUE;
  }
 }
 else if(pCW->message == WM_HOOKEX) 
 {
  UnhookWindowsHookEx(hHook);
  if (!bHooked)
   goto END;
  if(!SetWindowLong(hVLWnd, GWL_WNDPROC, (LONG)OldWndProc))
   goto END;
  FreeLibrary(hModuleDll);
  bHooked = FALSE;
 }
    
 END:
  return CallNextHookEx((HHOOK)pCW->wParam,nCode, wParam,lParam);
}


/*
NewWndProc - 23/05/2013
 Hàm nhận các sự kiện bên chương trình chính gửi qua
params:
 + HWND: HWnd cửa sổ đang chọn
 + UINT: Message của chương trình
 + WPARAM: Tham số wparam
 + LPARAM: Tham số lparam
return: 
*/
 
LRESULT CALLBACK NewWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{ 
 //g_logWriter.WriteLog(LOG_TYPE_DEBUG, L"WPARA-APPLY USE ITEM");

 switch(uMsg) 
 {
  case WM_COPYDATA: // get data from shared memory area
   
   
   COPYDATASTRUCT* pcds = (COPYDATASTRUCT *)lParam; 
   if (pcds->dwData == DATA_LOCKSOMEONEUSESKILL) // wparam
   {           
    iIdSkill = ((MYFUNCTION1 *)(pcds->lpData))->iIndex;
    iPosition = ((MYFUNCTION1 *)(pcds->lpData))->iPos;
   }

   
   AllocConsole(); 
   freopen("CONOUT$", "w", stdout);  
   
   cout << "[" << (int)iIdSkill << "] iSkill" << endl;
   cout << "[" << (int)iPosition << "] iPosition" << endl;

   break; 
 }


 if (!hWnd)
  return CallWindowProc(OldWndProc, hWnd, uMsg, wParam, lParam);
 DWORD pid;
 GetWindowThreadProcessId(hWnd, &pid);  
 

 // Ứng dụng Auto gửi rất nhiều message nhưng chỉ xử lý message WM_HOOK_WRITE thôi
 if (uMsg == WM_HOOK_WRITE)
 {   

  AllocConsole(); 
  freopen("CONOUT$", "w", stdout);  

  switch (wParam)
  {     
   case WPARAM_FUNCTION1:    
    MessageBox(NULL, L"received Function1 - lucky" , L"AutoPlay", 0);    
    cout << "[" << (int)lParam << "] Function1." << endl;
    break;

   case WPARAM_FUNCTION2:
    MessageBox(NULL, L"received Function2", L"AutoPlay", 0);
    cout << "[" << (int)lParam << "] Function2." << endl;
    break;


   /*case WPARAM_APPLYUSEITEM: 
    ApplyUseItem(pid, (int)lParam);       
    
    break;

   case WPARAM_LOCKSOMEONEUSESKILL:
    if (iPosition > 0 && iIdSkill > 0)
     LockSomeOneUseSkill(pid, iPosition, iIdSkill);
   
    break; */  
  }
 }
 return CallWindowProc(OldWndProc, hWnd, uMsg, wParam, lParam);
}


int InjectDll(HWND hWnd)
{  
 bUseMouse = FALSE;

 AllocConsole(); 
 freopen("CONOUT$", "w", stdout);  
 std::cout << "This works" << std::endl;
  
 if (!IsWindow(hWnd))
  return 0;

 hHook = SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC) HookProc, hModuleDll,  GetWindowThreadProcessId(hWnd,NULL));
 if(hHook == NULL)
 {
   //Error
  MessageBox(NULL,L"Can't set Hook KeyboardProc", L"Error", MB_OK);
  return 0;
 }
 else{
  SendMessage(hWnd, WM_HOOKEX, WPARAM(hHook), 1);
 }
 return 1;
}


int UnmapDll(HWND hWnd)
{ 
 if (!IsWindow(hWnd))
  return 0;
 HHOOK hHook = SetWindowsHookEx(WH_CALLWNDPROC,(HOOKPROC)HookProc, hModuleDll, GetWindowThreadProcessId(hWnd,NULL));
 if(hHook==NULL)
  return 0;


 FreeConsole();

 SendMessage(hWnd, WM_HOOKEX, (WPARAM)hHook, 0);
 return 1;
}


/************************************************************************/
//Controll.h


#define MSG_LBUTTONDOWN            0x2010001  // Khi user nhấn trái chuột
#define MSG_LBUTTONUP            0x2020001  // khi user nhã trái chuột


#if !defined INJECT_EX__H
 #define INJECT_EX__Info
 #ifdef INJECT_EX_EXPORTS
  #define HOOKDLL_API extern "C" __declspec(dllexport)
 #else
  #define HOOKDLL_API extern "C" __declspec(dllimport)
 #endif

 const UINT WM_HOOK_WRITE = RegisterWindowMessage(L"WM_HOOK_WRITE");
 const UINT WM_HOOKEX = RegisterWindowMessage(L"WM_HOOKEX_RK");
 
 #define pCW ((CWPSTRUCT*)lParam)
 
 HINSTANCE hModuleDll;
 HHOOK hHook;
 BOOL bHooked = 0;
 int iIdSkill = 0;
 int iPosition = 0;
 

 WNDPROC   OldWndProc = NULL;
 LRESULT CALLBACK NewWndProc(HWND,UINT,WPARAM,LPARAM);
 HOOKDLL_API int InjectDll(HWND hWnd);
 HOOKDLL_API int UnmapDll(HWND hWnd);
 
 // VịLH - Define prototype name --------
 DWORD GetItemIndex(DWORD, int);
 int ItemPosOnOneDimension_FirstPackage(DWORD, DWORD dwIndex);
 int ItemPosOnOneDimension_SeconcePackage(DWORD, DWORD dwIndex);
 void ApplyUseItem(DWORD, int);
 void ItemPosOnFirstPackage(DWORD, DWORD dwIndex, int& row, int& col);
 void ItemPosOnSeconcePackage(DWORD, DWORD dwIndex, int& row, int& col);
 void LockSomeOneUseSkill(DWORD pid, int iPos, int iIdSkill);
 void SpilitPosAndIdSkill(wchar_t* s);
#endif



Link C++
https://learn-tech-tips.blogspot.com/2015/10/dll-injection-and-exmaple-2.html
https://learn-tech-tips.blogspot.com/2015/08/dll-injection-exmaple.html


Thank you for reading this post. I hope you found it helpful and easy to follow. If you have any feedback or questions about Using C++ to Inject a DLL with C# Source Code , please share them in the comments below. I would love to hear from you and discuss this topic further
✋✋✋✋  Webzone Tech Tips, all things Tech Tips for web development  - I am Zidane, See you next time soon ✋✋✋✋

🙇🏼 We Appreciate Your Comments and Suggestions - Webzone - all things Tech Tips web development 🙇🏼
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com