Advertisement
Guest User

GTAVNoIntroOTF V 1.1

a guest
Sep 27th, 2016
925
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 28.01 KB | None | 0 0
  1. #define OUTPUT
  2. using Microsoft.Win32;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Linq;
  11. using System.Text.RegularExpressions;
  12. using System.Globalization;
  13.  
  14. namespace GTAVNoIntroOTF
  15. {
  16.  
  17.     public static class Program
  18.     {
  19.         //1.0.791.2 was old last version - 27.09.2016
  20.         private static bool debug;
  21.         public static void Main(string[] args)
  22.         {
  23.             bool patchintro = string.Join(" ", args).Contains("-dontpatchintro") ? false : true;
  24.             bool patchlegalmessages = string.Join(" ", args).Contains("-dontpatchlegalmessages") ? false : true;
  25.             bool setpriority = string.Join(" ", args).Contains("-dontsetpriority") ? false : true;
  26.             debug = string.Join(" ", args).Contains("-debug") ? true : false;
  27.  
  28.  
  29.             if (debug)
  30.             {
  31.                 NonStandardConsole.OpenConsole();
  32.                 Thread currentthread = Thread.CurrentThread;
  33.                 currentthread.CurrentCulture = CultureInfo.InvariantCulture;
  34.                 CustomOutput.ConsoleWriteandAddLog("[" + DateTime.Now.ToLongTimeString() + " " + DateTime.Now.ToLongDateString() + "]");
  35.  
  36.                 CustomOutput.ConsoleWriteandAddLog("Welcome to GTA V No Intro On The Fly V 1.1 - by Kryo4lex");
  37.                 CustomOutput.ConsoleWriteandAddLog("Passed commandline arguments:");
  38.                 CustomOutput.ConsoleWriteandAddLog(string.Join(" ", args));
  39.                 CustomOutput.ConsoleWriteandAddLog("Selected options:");
  40.                 if (patchintro)
  41.                     CustomOutput.ConsoleWriteandAddLog("Disable Intro: YES");
  42.                 else
  43.                     CustomOutput.ConsoleWriteandAddLog("Disable Intro: NO");
  44.                 if (patchlegalmessages)
  45.                     CustomOutput.ConsoleWriteandAddLog("Disable Legal Messages: YES");
  46.                 else
  47.                     CustomOutput.ConsoleWriteandAddLog("Disable Legal Messages: NO");
  48.                 if (setpriority)
  49.                     CustomOutput.ConsoleWriteandAddLog("Set process priority: YES");
  50.                 else
  51.                     CustomOutput.ConsoleWriteandAddLog("Set process priority: NO");
  52.  
  53.                 CustomOutput.ConsoleWriteandAddLog("Trying to get game path, version and start game...");
  54.             }
  55.  
  56.             if (!startrockstarversion())
  57.             {
  58.                 if (!startsteamversion())
  59.                 {
  60.                     if (debug)
  61.                     {
  62.                         CustomOutput.ConsoleWriteandAddLog("Unable to locate and therefore start GTA V... If game is installed run it manually!");
  63.                     }
  64.                 }
  65.             }
  66.  
  67.             GTAVNOIntroPatchOTF.Init(patchintro, patchlegalmessages,setpriority, debug);
  68.         }
  69.  
  70.         private static bool startrockstarversion()
  71.         {
  72.             try
  73.             {
  74.                 if (debug)
  75.                 {
  76.                     CustomOutput.ConsoleWriteandAddLog("Looking for GTA V Rockstar version...");
  77.                 }
  78.                 String installfolder = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rockstar Games\Grand Theft Auto V", "InstallFolder", null).ToString();
  79.                 if (installfolder != null)
  80.                 {
  81.                     if (System.IO.File.Exists(installfolder + @"\" + "GTAVLauncher.exe"))
  82.                     {
  83.                         if (debug)
  84.                         {
  85.                             CustomOutput.ConsoleWriteandAddLog("Rockstar version found at: ");
  86.                             CustomOutput.ConsoleWriteandAddLog(installfolder);
  87.                             FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(installfolder + @"\GTAVLauncher.exe");
  88.                             Console.WriteLine("Detected game version:\n" + myFileVersionInfo.FileVersion);
  89.                             CustomOutput.ConsoleWriteandAddLog("Starting game...");
  90.                         }
  91.                         Process.Start(installfolder + @"\GTAVLauncher.exe");
  92.                     }
  93.                     else
  94.                     {
  95.                         return false;
  96.                     }
  97.                 }
  98.                 else
  99.                 {
  100.                     return false;
  101.                 }
  102.             }
  103.             catch
  104.             {
  105.                 return false;
  106.             }
  107.  
  108.             return true;
  109.         }
  110.  
  111.         private static bool startsteamversion()
  112.         {
  113.             try
  114.             {
  115.                 if (debug)
  116.                 {
  117.                     CustomOutput.ConsoleWriteandAddLog("Looking for GTA V Steam version...");
  118.                 }
  119.                 string steamgtavinstalllocation = GTA_V_Steam_Locator.GTA_V_Folder();
  120.                 if (steamgtavinstalllocation != string.Empty)
  121.                 {
  122.                     if (System.IO.File.Exists(steamgtavinstalllocation + @"\" + "GTAVLauncher.exe"))
  123.                     {
  124.  
  125.                         if (debug)
  126.                         {
  127.                             CustomOutput.ConsoleWriteandAddLog("Steam version found at:");
  128.                             CustomOutput.ConsoleWriteandAddLog(steamgtavinstalllocation);
  129.                             FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(steamgtavinstalllocation + @"\" + "GTAVLauncher.exe");
  130.                             Console.WriteLine("Detected game version:\n" + myFileVersionInfo.FileVersion);
  131.  
  132.                             CustomOutput.ConsoleWriteandAddLog("Starting game...");
  133.                         }
  134.                         Process.Start("steam://rungameid/271590");
  135.                     }
  136.                     else
  137.                     {
  138.                         return false;
  139.                     }
  140.                 }
  141.                 else
  142.                 {
  143.                     return false;
  144.                 }
  145.  
  146.             }
  147.             catch
  148.             {
  149.                 return false;
  150.             }
  151.             return true;
  152.         }
  153.  
  154.     }
  155.  
  156.     public static class GTA_V_Steam_Locator
  157.     {
  158.         /// <summary>
  159.         /// Retrieves the Steam main installation folder from the registry
  160.         /// </summary>
  161.         public static string SteamFolder()
  162.         {
  163.             RegistryKey steamKey = Registry.LocalMachine.OpenSubKey("Software\\Valve\\Steam")
  164.                 ?? Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Valve\\Steam");
  165.             return steamKey.GetValue("InstallPath").ToString();
  166.         }
  167.  
  168.         /// <summary>
  169.         /// Retrieves a list of Steam library folders on this computer.
  170.         /// </summary>
  171.         public static List<string> SteamLibraryFolders()
  172.         {
  173.             List<string> folders = new List<string>();
  174.  
  175.             try
  176.             {
  177.                 string steamFolder = SteamFolder();
  178.                 folders.Add(steamFolder);
  179.  
  180.                 // the list of additional steam libraries can be found in the config.vdf file
  181.                 string configFile = Path.Combine(steamFolder, "config", "config.vdf");
  182.                 Regex regex = new Regex("BaseInstallFolder[^\"]*\"\\s*\"([^\"]*)\"");
  183.                 using (StreamReader reader = new StreamReader(configFile))
  184.                 {
  185.                     string line;
  186.                     while ((line = reader.ReadLine()) != null)
  187.                     {
  188.                         Match match = regex.Match(line);
  189.                         if (match.Success)
  190.                         {
  191.                             folders.Add(Regex.Unescape(match.Groups[1].Value));
  192.                         }
  193.                     }
  194.                 }
  195.             }
  196.             catch (Exception)
  197.             {
  198.                 // if there's any error in getting the Steam directory, ignore it for now.
  199.             }
  200.  
  201.             return folders;
  202.         }
  203.  
  204.         public static string GTA_V_Folder()
  205.         {
  206.             var appFolders = SteamLibraryFolders().Select(x => x + "\\SteamApps\\common");
  207.             foreach (var folder in appFolders)
  208.             {
  209.                 try
  210.                 {
  211.                     var matches = Directory.GetDirectories(folder, "Grand Theft Auto V");
  212.                     if (matches.Length >= 1)
  213.                     {
  214.                         return matches[0];
  215.                     }
  216.                 }
  217.                 catch (DirectoryNotFoundException)
  218.                 {
  219.                     //continue;
  220.                 }
  221.  
  222.             }
  223.  
  224.             return String.Empty;
  225.  
  226.  
  227.         }
  228.     }
  229.  
  230.     public class GTAVNOIntroPatchOTF
  231.     {
  232.  
  233.         #region Constants
  234.         const int PROCESS_ALL_ACCESS = (int)(0x001F0FFF);
  235.         const UInt64 BUFFER_SIZE = 8192 * 4;
  236.         #endregion
  237.  
  238.         #region Windows DLL Imports
  239.  
  240.         [DllImport("kernel32.dll")]
  241.         private static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
  242.  
  243.         [DllImport("kernel32.dll")]
  244.         private static extern bool ReadProcessMemory(int hProcess,
  245.             UInt64 lpBaseAddress, byte[] lpBuffer, UInt64 dwSize, ref UInt64 lpNumberOfBytesRead);
  246.  
  247.         [DllImport("Kernel32.dll")]
  248.         private static extern bool WriteProcessMemory(int handle, UInt64 lpBaseAddress, byte[] lpBuffer, int nSize, UInt64 lpNumberOfBytesWritten);
  249.         /*
  250.         [DllImport("kernel32.dll", SetLastError = true)]
  251.         internal static extern bool VirtualProtect(UInt64 address, int size, UInt64 newProtect, out UInt64 oldProtect);
  252.  
  253.  
  254.         /*
  255.         [DllImport("USER32.DLL")]
  256.         private static extern bool IsWindowVisible(IntPtr hWnd);
  257.         */
  258.  
  259.         [DllImport("user32.dll")]
  260.         [return: MarshalAs(UnmanagedType.Bool)]
  261.         private static extern bool IsWindow(IntPtr hWnd);
  262.  
  263.         [DllImport("kernel32.dll")]
  264.         private static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
  265.         [DllImport("kernel32.dll")]
  266.         private static extern uint SuspendThread(IntPtr hThread);
  267.         [DllImport("kernel32.dll")]
  268.         private static extern int ResumeThread(IntPtr hThread);
  269.  
  270.         [DllImport("kernel32.dll")]
  271.         [return: MarshalAs(UnmanagedType.Bool)]
  272.         private static extern bool CloseHandle(IntPtr hObject);
  273.  
  274.         #endregion
  275.  
  276.         private static IntPtr processHandle;
  277.         private static bool Patchintro;
  278.         private static bool Patchlegalmessages;
  279.         private static bool Debug;
  280.         private static bool Setpriotity;
  281.         private static Stopwatch stopwatch;
  282.  
  283.         public static void Init(bool patchintro, bool patchlegalmessages,bool setpriority, bool debug)
  284.         {
  285.             Patchintro = patchintro;
  286.             Patchlegalmessages = patchlegalmessages;
  287.             Debug = debug;
  288.             Setpriotity = setpriority;
  289.             Thread thread1 = new Thread(main);
  290.             thread1.Start();
  291.         }
  292.  
  293.         private static void main()
  294.         {
  295.             if (Debug)
  296.             {
  297.                 CustomOutput.ConsoleWriteandAddLog("Waiting for the GTA V process...");
  298.             }
  299.             //CpuAffinity.SetCurrentThreadToHaveCpuAffinityFor(3);
  300.             //Waiting for the GTA V process
  301.             while (!IsProcessOpen("GTA5"))
  302.             {
  303.                 System.Threading.Thread.Sleep(5);
  304.             }
  305.  
  306.             Process process = Process.GetProcessesByName("GTA5").First<Process>();;
  307.             if (Debug)
  308.             {
  309.                 CustomOutput.ConsoleWriteandAddLog((char)34 + "GTA5" + (char)34 + " process (exe) found!");
  310.                 CustomOutput.ConsoleWriteandAddLog("Process handle: " + Convert.ToString(process.Handle));
  311.                 CustomOutput.ConsoleWriteandAddLog("Process MainModule.BaseAddress: 0x" + process.MainModule.BaseAddress.ToString("X"));
  312.                 CustomOutput.ConsoleWriteandAddLog("Waiting for the GTA V process window...");
  313.             }
  314.             //The memory we are looking for only exists, if the game exe create a window
  315.             //while (!IsWindowVisible(process.MainWindowHandle))
  316.             /*
  317.             while (!IsWindow(process.MainWindowHandle))
  318.             {
  319.                 System.Threading.Thread.Sleep(5);
  320.             }
  321.             */
  322.             process.WaitForInputIdle();
  323.             if (Debug)
  324.             {
  325.                 CustomOutput.ConsoleWriteandAddLog("Process window found!");
  326.  
  327.  
  328.                 // Create new stopwatch.
  329.                 stopwatch = new Stopwatch();
  330.  
  331.                 // Begin timing.
  332.                 stopwatch.Start();
  333.  
  334.                 CustomOutput.ConsoleWriteandAddLog("Suspending process!");
  335.             }
  336.  
  337.             //game window exists --> memory we are looking for exists
  338.             //stop exe process that it can't load anything
  339.             SuspendProcess(process.Id);
  340.             //if(process.Threads[0].ThreadState == ThreadState.)
  341.  
  342.             if (Debug)
  343.             {
  344.                 CustomOutput.ConsoleWriteandAddLog("Opening process handle...");
  345.             }
  346.  
  347.             //Open process to access it
  348.             processHandle = OpenProcess(PROCESS_ALL_ACCESS, false, process.Id);
  349.  
  350.  
  351.             //CustomOutput.ConsoleWriteandAddLog("Disable Intro:");
  352.             if (Patchintro)
  353.             {
  354.                 DisableIntro();
  355.             }
  356.  
  357.             //CustomOutput.ConsoleWriteandAddLog("Disable Legal Messages:");
  358.             if (Patchlegalmessages)
  359.             {
  360.                 DisableLegalMessages();
  361.             }
  362.             /*
  363.             int cpuaffinitybitmask = Convert.ToInt32("1111", 2);
  364.             process.ProcessorAffinity = (IntPtr)cpuaffinitybitmask;
  365.             if (Debug)
  366.             {
  367.                 CustomOutput.ConsoleWriteandAddLog("Setting process CPU affinity to bitmask " + Convert.ToString(cpuaffinitybitmask) +  " ...");
  368.             }
  369. */
  370.  
  371.             if (Setpriotity)
  372.             {
  373.                 if (Debug)
  374.                 {
  375.                     CustomOutput.ConsoleWriteandAddLog("Setting process priority to " + ProcessPriorityClass.RealTime.ToString());
  376.                 }
  377.  
  378.                 process.PriorityClass = ProcessPriorityClass.RealTime;
  379.             }
  380.  
  381.             if (Debug)
  382.             {
  383.                 CustomOutput.ConsoleWriteandAddLog("Resuming process...");
  384.             }
  385.             //Continue game process, I guess you want to play right?
  386.             ResumeProcess(process.Id);
  387.  
  388.  
  389.  
  390.  
  391.             if (Debug)
  392.             {
  393.                 CustomOutput.ConsoleWriteandAddLog("Closing process handle...");
  394.             }
  395.             //Close handle that we have no access problems...
  396.  
  397.             CloseHandle((IntPtr)processHandle);
  398.             if (Debug)
  399.             {
  400.                 CustomOutput.ConsoleWriteandAddLog("FINISHED!");
  401.  
  402.                 //Stop timing.
  403.                 stopwatch.Stop();
  404.  
  405.                 //Write result.
  406.                 CustomOutput.ConsoleWriteandAddLog("Total time for memory search and patching in ms: " + stopwatch.Elapsed.TotalMilliseconds.ToString());
  407.                 Console.ReadLine();
  408.  
  409.             }
  410.  
  411.             Environment.Exit(0);
  412.         }
  413.  
  414.         #region Main functions
  415.  
  416.         private static void DisableIntro()
  417.         {
  418.             byte[] im_pattern = Encoding.ASCII.GetBytes("rockstar_logos");
  419.  
  420.             bool found = false;
  421.  
  422.             UInt64 bytesRead = 0;
  423.             UInt64 n_Size = BUFFER_SIZE;
  424.             UInt64 n_Size_pattern = (ulong)im_pattern.Length;
  425.             byte[] buffer = new byte[n_Size];
  426.             byte[] buffer_pattern = new byte[n_Size_pattern];
  427.  
  428.             Process process = Process.GetProcessesByName("GTA5")[0];
  429.  
  430.             UInt64 address = (UInt64)process.MainModule.BaseAddress;
  431.  
  432.             if (Debug)
  433.             {
  434.                 CustomOutput.ConsoleWriteandAddLog("Looking for the Intro address...");
  435.             }
  436.  
  437.             while (!found)
  438.             {
  439.  
  440.                 ReadProcessMemory((int)processHandle, address, buffer, (UInt64)buffer.Length, ref bytesRead);
  441.  
  442.                 uint index = 0;
  443.  
  444.                 //when we found what we are looking for, display the addresses and patch the memory
  445.                 if (IndexOf(buffer, im_pattern, out index))
  446.                 {
  447.                     ReadProcessMemory((int)processHandle, address + index, buffer_pattern, (UInt64)n_Size_pattern, ref bytesRead);
  448.  
  449.                     if (MaskCheck(buffer_pattern, im_pattern, "xxxxxxxxxxxxxx"))
  450.                     {
  451.                         if (Debug)
  452.                         {
  453.                             CustomOutput.ConsoleWriteandAddLog("Found Intro Movies at: 0x" + (index + address).ToString("X"));
  454.                             CustomOutput.ConsoleWriteandAddLog("Applying memory patch for Intro Movies...");
  455.                         }
  456.                         //Console.ReadLine();
  457.                         //this is the most important function, the shit where magic happens!!!!
  458.                         //write the name of a file which for sure doesn't exist
  459.                         if (WriteString((int)processHandle, address + index, "lolololo_logos.bik"))
  460.                         {
  461.                             if (Debug)
  462.                             {
  463.                                 CustomOutput.ConsoleWriteandAddLog("Memory patch for Intro Movies successful: YES");
  464.                             }
  465.                             ////Console.Beep(500, 500);
  466.                         }
  467.                         else
  468.                         {
  469.                             //should never happen lol...
  470.                             if (Debug)
  471.                             {
  472.                                 CustomOutput.ConsoleWriteandAddLog("Memory patch for Intro Movies successful: NO");
  473.                             }
  474.                         }
  475.                         found = true;
  476.                     }
  477.                 }
  478.  
  479.                 address += n_Size;
  480.             }
  481.         }
  482.         private static void DisableLegalMessages()
  483.         {
  484.             //                     x     x     x     ?     ?     ?     x     x     x     ?     ?     ?     x     x     x     x
  485.             //the value under this line was for PC below 1.0.678.1
  486.             //byte[] lm_pattern = { 0x72, 0x1F, 0xE8, 0x12, 0x8D, 0xFB, 0x00, 0x8B, 0x0D, 0x34, 0x7F, 0xC3, 0x01, 0xFF, 0xC1, 0x48 };
  487.             byte[] lm_pattern = { 0x72, 0x1F, 0xE8, 0x12, 0x8D, 0xFB, 0x01, 0x8B, 0x0D, 0x34, 0x7F, 0xC3, 0x01, 0xFF, 0xC1, 0x48 };
  488.             bool found = false;
  489.             //the mask under this line was for PC below 1.0.678.1
  490.             //string mask = "xxx???xxx???xxxx";
  491.             string mask = "xxx????xx???xxxx";
  492.  
  493.             UInt64 bytesRead = 0;
  494.             UInt64 n_Size = BUFFER_SIZE;
  495.             UInt64 n_Size_pattern = (ulong)lm_pattern.Length;
  496.             byte[] buffer = new byte[n_Size];
  497.             byte[] buffer_pattern = new byte[n_Size_pattern];
  498.             byte[] nop_data = { 0x90, 0x90 };
  499.             //byte[] nop_data = { 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90 };
  500.             Process process = Process.GetProcessesByName("GTA5")[0];
  501.  
  502.             UInt64 address = (UInt64)process.MainModule.BaseAddress;
  503.  
  504.             if (Debug)
  505.             {
  506.                 CustomOutput.ConsoleWriteandAddLog("Looking for the legal messages address...");
  507.             }
  508.  
  509.             while (!found)
  510.             {
  511.  
  512.                 ReadProcessMemory((int)processHandle, address, buffer, (UInt64)buffer.Length, ref bytesRead);
  513.  
  514.                 uint index = 0;
  515.  
  516.                 //when we found what we are looking for, display the addresses and patch the memory
  517.                 if (IndexOf(buffer, new byte[] { lm_pattern[0], lm_pattern[1], lm_pattern[2] }, out index))
  518.                 {
  519.                     ReadProcessMemory((int)processHandle, address + index, buffer_pattern, (UInt64)n_Size_pattern, ref bytesRead);
  520.  
  521.                     if (MaskCheck(buffer_pattern, lm_pattern, mask))
  522.                     {
  523.                         if (Debug)
  524.                         {
  525.                             CustomOutput.ConsoleWriteandAddLog("Found Legal Messages at: 0x" + (index + address).ToString("X"));
  526.                             CustomOutput.ConsoleWriteandAddLog("Applying memory patch for Legal Messages...");
  527.                         }
  528.                         //Console.ReadLine();
  529.                         //this is the most important function, the shit where magic happens!!!!
  530.                         //Legal Messages have no movie files. They are "generated".
  531.                         //Here we overwrite the internal programm code which displays them with NOPs
  532.                         if (WriteProcessMemory((int)processHandle, address + index, nop_data, nop_data.Length, 0))
  533.                         {
  534.                             if (Debug)
  535.                             {
  536.                                 CustomOutput.ConsoleWriteandAddLog("Memory patch for Legal Messages successful: YES");
  537.                             }
  538.                             ////Console.Beep(500, 500);
  539.                         }
  540.                         else
  541.                         {
  542.                             if (Debug)
  543.                             {
  544.                                 CustomOutput.ConsoleWriteandAddLog("Memory patch for Legal Messages successful: NO");
  545.                             }
  546.                         }
  547.  
  548.                         found = true;
  549.                     }
  550.                 }
  551.  
  552.                 address += n_Size;
  553.             }
  554.         }
  555.  
  556.         #endregion
  557.  
  558.         #region Memory helper functions
  559.  
  560.         private static bool MaskCheck(byte[] btsrc, byte[] btPattern, string strMask)
  561.         {
  562.             // Loop the pattern and compare to the mask and dump.
  563.             for (int x = 0; x < btPattern.Length; x++)
  564.             {
  565.                 // If the mask char is a wildcard, just continue.
  566.                 if (strMask[x] == '?')
  567.                     continue;
  568.  
  569.                 // If the mask char is not a wildcard, ensure a match is made in the pattern.
  570.                 if ((strMask[x] == 'x') && (btsrc[x] != btPattern[x]))
  571.                     return false;
  572.             }
  573.  
  574.             // The loop was successful so we found the pattern.
  575.             return true;
  576.         }
  577.  
  578.         private static bool WriteString(int handle, UInt64 address, string value)
  579.         {
  580.             byte[] data = Encoding.Default.GetBytes(value + "\0");
  581.             return WriteProcessMemory(handle, address, data, data.Length, 0);
  582.         }
  583.  
  584.         private static bool WriteInt(int handle, UInt64 address, int value)
  585.         {
  586.             byte[] data = BitConverter.GetBytes(value);
  587.             return WriteProcessMemory(handle, address, data, data.Length, 0);
  588.         }
  589.  
  590.         private static bool IndexOf(byte[] arrayToSearchThrough, byte[] patternToFind, out uint index)
  591.         {
  592.             if (patternToFind.Length > arrayToSearchThrough.Length)
  593.             {
  594.                 index = 0;
  595.                 return false;
  596.             }
  597.             for (uint i = 0; i < arrayToSearchThrough.Length - patternToFind.Length; i++)
  598.             {
  599.                 bool found = true;
  600.                 for (uint j = 0; j < patternToFind.Length; j++)
  601.                 {
  602.                     if (arrayToSearchThrough[i + j] != patternToFind[j])
  603.                     {
  604.                         found = false;
  605.                         break;
  606.                     }
  607.                 }
  608.                 if (found)
  609.                 {
  610.                     index = i;
  611.                     return true;
  612.                 }
  613.             }
  614.             index = 0;
  615.             return false;
  616.         }
  617.         #endregion
  618.  
  619.         #region Process/Thread functions
  620.  
  621.         private static bool IsProcessOpen(string name)
  622.         {
  623.             foreach (Process clsProcess in Process.GetProcesses())
  624.             {
  625.                 if (clsProcess.ProcessName.Contains(name))
  626.                 {
  627.                     return true;
  628.                 }
  629.             }
  630.             return false;
  631.         }
  632.  
  633.         [Flags]
  634.         private enum ThreadAccess : int
  635.         {
  636.             TERMINATE = (0x0001),
  637.             SUSPEND_RESUME = (0x0002),
  638.             GET_CONTEXT = (0x0008),
  639.             SET_CONTEXT = (0x0010),
  640.             SET_INFORMATION = (0x0020),
  641.             QUERY_INFORMATION = (0x0040),
  642.             SET_THREAD_TOKEN = (0x0080),
  643.             IMPERSONATE = (0x0100),
  644.             DIRECT_IMPERSONATION = (0x0200)
  645.         }
  646.  
  647.         private static void SuspendProcess(int pid)
  648.         {
  649.             var process = Process.GetProcessById(pid);
  650.  
  651.             if (process.ProcessName == string.Empty)
  652.                 return;
  653.  
  654.             foreach (ProcessThread pT in process.Threads)
  655.             {
  656.                 IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
  657.  
  658.                 if (pOpenThread == IntPtr.Zero)
  659.                 {
  660.                     continue;
  661.                 }
  662.  
  663.                 SuspendThread(pOpenThread);
  664.  
  665.                 CloseHandle(pOpenThread);
  666.             }
  667.         }
  668.         private static void ResumeProcess(int pid)
  669.         {
  670.             var process = Process.GetProcessById(pid);
  671.  
  672.             if (process.ProcessName == string.Empty)
  673.                 return;
  674.  
  675.             foreach (ProcessThread pT in process.Threads)
  676.             {
  677.                 IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
  678.  
  679.                 if (pOpenThread == IntPtr.Zero)
  680.                 {
  681.                     continue;
  682.                 }
  683.  
  684.                 var suspendCount = 0;
  685.                 do
  686.                 {
  687.                     suspendCount = ResumeThread(pOpenThread);
  688.                 } while (suspendCount > 0);
  689.  
  690.                 CloseHandle(pOpenThread);
  691.             }
  692.         }
  693.         #endregion
  694.  
  695.     }
  696.  
  697.     public static class NonStandardConsole
  698.     {
  699.         [DllImport("kernel32.dll", SetLastError = true)]
  700.         static extern bool AllocConsole();
  701.  
  702.         [DllImport("kernel32.dll", SetLastError = true)]
  703.         static extern bool FreeConsole();
  704.  
  705.         [DllImport("kernel32", SetLastError = true)]
  706.         static extern bool AttachConsole(int dwProcessId);
  707.  
  708.         [DllImport("user32.dll")]
  709.         static extern IntPtr GetForegroundWindow();
  710.  
  711.         [DllImport("user32.dll", SetLastError = true)]
  712.         static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
  713.  
  714.         public static void CloseConsole()
  715.         {
  716.             FreeConsole();
  717.         }
  718.  
  719.         public static void OpenConsole()
  720.         {
  721.             //Get a pointer to the forground window.  The idea here is that
  722.             //IF the user is starting our application from an existing console
  723.             //shell, that shell will be the uppermost window.  We'll get it
  724.             //and attach to it
  725.             IntPtr ptr = GetForegroundWindow();
  726.  
  727.             int u;
  728.  
  729.             GetWindowThreadProcessId(ptr, out u);
  730.  
  731.             Process process = Process.GetProcessById(u);
  732.  
  733.             if (process.ProcessName == "cmd")    //Is the uppermost window a cmd process?
  734.             {
  735.                 AttachConsole(process.Id);
  736.  
  737.                 //we have a console to attach to ..
  738.                 //Console.WriteLine("hello. It looks like you started me from an existing console.");
  739.             }
  740.             else
  741.             {
  742.                 //no console AND we're in console mode ... create a new console.
  743.                 AllocConsole();
  744.                 //Console.WriteLine(@"hello. It looks like you double clicked me to start AND you want console mode.  Here's a new console.");
  745.             }
  746.         }
  747.  
  748.     }
  749.  
  750.     public static class CustomOutput
  751.     {
  752.  
  753.         public static void ConsoleWriteandAddLog(string text)
  754.         {
  755.             Console.WriteLine(text);
  756.             try
  757.             {
  758.                 using (StreamWriter w = File.AppendText("log.txt"))
  759.                 {
  760.                     w.WriteLine(text);
  761.                 }
  762.             }
  763.             catch
  764.             {
  765.  
  766.             }
  767.         }
  768.     }
  769.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement