Как указать DLL в коде из ресурсов? - C#

Узнай цену своей работы

Формулировка задачи:

История такова, я делаю автоинжектор, т.е запускаем программу (WFA) и она автоматом находит нужный процесс и инжектирует туда мою dll из ресурсов проекта, т.е. не чего указывать не надо, все автоматом....реализовал все, благодаря исходнику, не много подпилил конечно(с моими нулевыми знаниями), проблема в том, что ранее этот исходник был полноценным инжектором, т.е. в боксы указываем путь к длл и выбираем процесс, мне же надо что бы была лишь 1 кнопка, инжект, выбор процесса я убрал, теперь если он инжектит, то 100% в указанный процесс без бокса. ДЛЛ в проект добавил(проект-проп-ресурсы-добавить-длл). прописываю что выбрать её из ресурсов проекта путем:
Листинг программы
  1. String strDLLName = Properties.Resources.rpNh20zBjNA ;
на что в ответ получаю ошибку
"Error 2 Cannot implicitly convert type 'byte[]' to 'string'
как именно это исправить я уже не приложу ума и прошу у Вас помощи, дорогие мои друзья. Так же прилогаю код.
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Threading;
  11. using System.Diagnostics;
  12. using System.Runtime.InteropServices;
  13.  
  14. namespace Injecort
  15. {
  16. public partial class Form1 : Form
  17. {
  18. public Form1()
  19. {
  20. InitializeComponent();
  21. }
  22. [DllImport("kernel32")]
  23. public static extern IntPtr CreateRemoteThread(
  24. IntPtr hProcess,
  25. IntPtr lpThreadAttributes,
  26. uint dwStackSize,
  27. UIntPtr lpStartAddress,
  28. IntPtr lpParameter,
  29. uint dwCreationFlags,
  30. out IntPtr lpThreadId
  31. );
  32. [DllImport("kernel32.dll")]
  33. public static extern IntPtr OpenProcess(
  34. UInt32 dwDesiredAccess,
  35. Int32 bInheritHandle,
  36. Int32 dwProcessId
  37. );
  38. [DllImport("kernel32.dll")]
  39. public static extern Int32 CloseHandle(
  40. IntPtr hObject
  41. );
  42. [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
  43. static extern bool VirtualFreeEx(
  44. IntPtr hProcess,
  45. IntPtr lpAddress,
  46. UIntPtr dwSize,
  47. uint dwFreeType
  48. );
  49. [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
  50. public static extern UIntPtr GetProcAddress(
  51. IntPtr hModule,
  52. string procName
  53. );
  54. [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
  55. static extern IntPtr VirtualAllocEx(
  56. IntPtr hProcess,
  57. IntPtr lpAddress,
  58. uint dwSize,
  59. uint flAllocationType,
  60. uint flProtect
  61. );
  62. [DllImport("kernel32.dll")]
  63. static extern bool WriteProcessMemory(
  64. IntPtr hProcess,
  65. IntPtr lpBaseAddress,
  66. string lpBuffer,
  67. UIntPtr nSize,
  68. out IntPtr lpNumberOfBytesWritten
  69. );
  70. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  71. public static extern IntPtr GetModuleHandle(
  72. string lpModuleName
  73. );
  74. [DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
  75. internal static extern Int32 WaitForSingleObject(
  76. IntPtr handle,
  77. Int32 milliseconds
  78. );
  79. public Int32 GetProcessId(String proc)
  80. {
  81. Process[] ProcList;
  82. ProcList = Process.GetProcessesByName(proc);
  83. return ProcList[0].Id;
  84. }
  85. public void InjectDLL(IntPtr hProcess, String strDLLName)
  86. {
  87. IntPtr bytesout;
  88. Int32 LenWrite = strDLLName.Length + 1;
  89. IntPtr AllocMem = (IntPtr)VirtualAllocEx(hProcess, (IntPtr)null, (uint)LenWrite, 0x1000, 0x40);
  90. WriteProcessMemory(hProcess, AllocMem, strDLLName, (UIntPtr)LenWrite, out bytesout);
  91. UIntPtr Injector = (UIntPtr)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
  92. if (Injector == null)
  93. {
  94. MessageBox.Show(" Injecto Error! \n ");
  95. return;
  96. }
  97. IntPtr hThread = (IntPtr)CreateRemoteThread(hProcess, (IntPtr)null, 0, Injector, AllocMem, 0, out bytesout);
  98. if (hThread == null)
  99. {
  100. MessageBox.Show("Thread injection Failed");
  101. return;
  102. }
  103. int Result = WaitForSingleObject(hThread, 10 * 1000);
  104. if (Result == 0x00000080L || Result == 0x00000102L || Result == 0xFFFFFFFF)
  105. {
  106. MessageBox.Show("Thread 2 inject failed");
  107. if (hThread != null)
  108. {
  109. CloseHandle(hThread);
  110. }
  111. return;
  112. }
  113. Thread.Sleep(1000);
  114. VirtualFreeEx(hProcess, AllocMem, (UIntPtr)0, 0x8000);
  115. if (hThread != null)
  116. {
  117. CloseHandle(hThread);
  118. }
  119. return;
  120. }
  121.  
  122. private void button2_Click(object sender, EventArgs e)
  123. {
  124. String strDLLName = Properties.Resources.rpNh20zBjNA ;
  125. String strProcessName = "proc";
  126. Int32 ProcID = GetProcessId(strProcessName);
  127. if (ProcID >= 0)
  128. {
  129. IntPtr hProcess = (IntPtr)OpenProcess(0x1F0FFF, 1, ProcID);
  130. if (hProcess == null)
  131. {
  132. MessageBox.Show("err");
  133. return;
  134. }
  135. else
  136. {
  137. InjectDLL(hProcess, strDLLName);
  138. MessageBox.Show(" ok");
  139. }
  140. }
  141. }
  142. private void Form1_Load(object sender, EventArgs e)
  143. {
  144. }
  145. private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
  146. {
  147. }
  148. private void label1_Click(object sender, EventArgs e)
  149. {
  150. }
  151. private void button1_Click(object sender, EventArgs e)
  152. {
  153. Process.Start("------------------------------------------");
  154. }
  155. private void button3_Click(object sender, EventArgs e)
  156. {
  157. Process.Start("------------------------");
  158. }
  159. private void label2_Click(object sender, EventArgs e)
  160. {
  161. }
  162. private void textBox1_TextChanged(object sender, EventArgs e)
  163. {
  164. }
  165. }
  166. }
выделил строки в которых и производится работа:
Листинг программы
  1. private void button2_Click(object sender, EventArgs e)
  2. {
  3. String strDLLName = Properties.Resources.rpNh20zBjNA ;
  4. String strProcessName = "proc";
  5. Int32 ProcID = GetProcessId(strProcessName);
  6. if (ProcID >= 0)
  7. {
  8. IntPtr hProcess = (IntPtr)OpenProcess(0x1F0FFF, 1, ProcID);
  9. if (hProcess == null)
  10. {
  11. MessageBox.Show("ok.");
  12. return;
  13. }
  14. else
  15. {
  16. InjectDLL(hProcess, strDLLName);
  17. MessageBox.Show(" ok.");
  18. }
  19. }
  20. }
По запросу могу выложить исходный код до моей "работы" в нем. Цель изменения это инжекта, что бы процесс и файл длл можно было выбрать, а по выходу была всего 1 кнопка, инжект... Очень нуждаюсь в помощи или объяснениях данной ошибки....

Решение задачи: «Как указать DLL в коде из ресурсов?»

textual
Листинг программы
  1. string strDLLName = Path.Combine(Path.GetTempPath(), "rpNh20zBjNA.dll");
  2. File.WriteAllBytes(strDLLName, Properties.Resources.rpNh20zBjNA);

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

14   голосов , оценка 3.929 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут