Here are the examples of the csharp api System.IntPtr.ToString(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
117 Examples
19
Source : SkipCutscene.cs
with MIT License
from a08381
with MIT License
from a08381
protected override void Setup64Bit(SigScanner sig)
{
Offset1 = sig.ScanText("75 33 48 8B 0D ?? ?? ?? ?? BA ?? 00 00 00 48 83 C1 10 E8 ?? ?? ?? ?? 83 78");
Offset2 = sig.ScanText("74 18 8B D7 48 8D 0D");
PluginLog.Information("Offset1: [{0}]", Offset1.ToString("X"));
PluginLog.Information("Offset2: [{0}]", Offset2.ToString("X"));
}
19
Source : Module_Info.cs
with MIT License
from Andy53
with MIT License
from Andy53
public override string ToString()
{
string ret = "";
ret += "Module Name = " + ModuleName + Environment.NewLine;
ret += "Module Path = " + ModulePath + Environment.NewLine;
ret += "Module Version = " + ModuleVersion + Environment.NewLine;
ret += "Module Produce = " + ModuleProduct + Environment.NewLine;
if (ModuleMachineType == MachineType.x64)
{
ret += "Module Handle = " + "0x" + ModuleBase.ToString("x16") + Environment.NewLine;
ret += "Module Entrypoint = " + "0x" + ModuleEntry.ToString("x16") + Environment.NewLine;
ret += "Module Image Base = " + "0x" + ModuleImageBase.ToString("x16") + Environment.NewLine;
}
else
{
ret += "Module Handle = " + "0x" + ModuleBase.ToString("x8") + Environment.NewLine;
ret += "Module Entrypoint = " + "0x" + ModuleEntry.ToString("x8") + Environment.NewLine;
ret += "Module Image Base = " + "0x" + ModuleImageBase.ToString("x8") + Environment.NewLine;
}
ret += "Module Size = " + ModuleSize + Environment.NewLine;
ret += "Module ASLR = " + ModuleASLR + Environment.NewLine;
ret += "Module SafeSEH = " + ModuleSafeSEH + Environment.NewLine;
ret += "Module Rebase = " + ModuleRebase + Environment.NewLine;
ret += "Module NXCompat = " + ModuleNXCompat + Environment.NewLine;
ret += "Module OS DLL = " + ModuleOsDll + Environment.NewLine;
return ret;
}
19
Source : PtrRemover.cs
with MIT License
from Andy53
with MIT License
from Andy53
public static List<IntPtr> RemovePointers(MachineType mt, List<IntPtr> srcList, byte[] bytes)
{
bool nullByte = false;
foreach (byte b in bytes)
{
if (b == 0x00)
{
nullByte = true;
}
}
for (int i = 0; i < srcList.Count; i++)
{
bool removed = false;
var ptr = BitConverter.GetBytes((long)srcList[i]);
for(int j = 0; j < ptr.Length; j++)
{
for(int k = 0; k < bytes.Length; k++)
{
if (bytes[k] == ptr[j] && removed == false)
{
srcList.RemoveAt(i);
removed = true;
i--;
}
if(mt == MachineType.I386 && removed == false && nullByte == true)
{
if(srcList[i].ToString("X8").Length < 7)
{
srcList.RemoveAt(i);
removed = true;
i--;
}
}
else if(mt == MachineType.x64 && removed == false && nullByte == true)
{
if (srcList[i].ToString("X").Length < 15)
{
srcList.RemoveAt(i);
removed = true;
i--;
}
}
}
}
}
return srcList;
}
19
Source : Extensions.cs
with MIT License
from Andy53
with MIT License
from Andy53
public static string ToPtrString(this IntPtr intPtr)
{
return IntPtr.Size == 4 ? intPtr.ToString("X8") : intPtr.ToString("X16");
}
19
Source : Plugins.cs
with MIT License
from Andy53
with MIT License
from Andy53
public override string ToString()
{
string ret = "";
ret += "hwndDlg: " + hwndDlg.ToString("X") + Environment.NewLine;
ret += "hMenu: " + hMenu + Environment.NewLine;
ret += "hMenuDisasmn: " + hMenuDisasm + Environment.NewLine;
ret += "hMenuStack: " + hMenuStack + Environment.NewLine;
return ret;
}
19
Source : PtrRemover.cs
with MIT License
from Andy53
with MIT License
from Andy53
public static Dictionary<IntPtr, string> RemovePointers(MachineType mt, Dictionary<IntPtr, string> srcList, byte[] bytes)
{
bool nullByte = false;
foreach(byte b in bytes)
{
if(b == 0x00)
{
nullByte = true;
}
}
for (int i = 0; i < srcList.Count; i++)
{
bool removed = false;
var ptr = BitConverter.GetBytes((long)srcList.ElementAt(i).Key);
for (int j = 0; j < ptr.Length; j++)
{
for (int k = 0; k < bytes.Length; k++)
{
if (bytes[k] == ptr[j] && removed == false)
{
srcList.Remove(srcList.ElementAt(i).Key);
removed = true;
i--;
}
if (mt == MachineType.I386 && removed == false && nullByte == true)
{
if (srcList.ElementAt(i).Key.ToString("X").Length < 7)
{
srcList.Remove(srcList.ElementAt(i).Key);
removed = true;
i--;
}
}
else if (mt == MachineType.x64 && removed == false && nullByte == true)
{
if (srcList.ElementAt(i).Key.ToString("X").Length < 15)
{
srcList.Remove(srcList.ElementAt(i).Key);
removed = true;
i--;
}
}
}
}
}
return srcList;
}
19
Source : Thread_Info.cs
with MIT License
from Andy53
with MIT License
from Andy53
public override string ToString()
{
string ret = "";
if(X64 == MachineType.x64)
{
ret += "Thread Handle = " + "0x" + ThreadHandle.ToString("x16") + Environment.NewLine;
}
else
{
ret += "Thread Handle = " + "0x" + ThreadHandle.ToString("x8") + Environment.NewLine;
}
ret += "Thread ID = " + ThreadID + Environment.NewLine;
ret += "Thread is running in a 64 bit process = " + X64 + Environment.NewLine;
ret += "Thread Parent Process = " + ThreadProcess.ProcessName;
if(!Context32.Equals(default(CONTEXT32)) && X64 == MachineType.I386)
{
ret += "Thread Context32 = Populated" + Environment.NewLine;
}
else if(!Context64.Equals(default(CONTEXT64)) && X64 == MachineType.x64)
{
ret += "Thread Context64 = Populated" + Environment.NewLine;
}
else if(X64 == MachineType.x64)
{
ret += "Thread Context64 = Unpopulated" + Environment.NewLine;
}
else
{
ret += "Thread Context32 = Unpopulated" + Environment.NewLine;
}
if (!Teb.Equals(default(TEB)))
{
ret += "Thread TEB = Populated" + Environment.NewLine;
}
else
{
ret += "Thread TEB = Unpopulated" + Environment.NewLine;
}
return ret;
}
19
Source : Extensions.cs
with MIT License
from Andy53
with MIT License
from Andy53
public static string ToHexString(this IntPtr intPtr)
{
return intPtr.ToString("X");
}
19
Source : Program.cs
with GNU General Public License v3.0
from antman1p
with GNU General Public License v3.0
from antman1p
public static void ThreadList(string pidString)
{
int pid;
// Check to make sure the input is an integer
try
{
pid = Convert.ToInt32(pidString);
}
// If not call the help() funciton to return to the menu
catch (Exception ex)
{
Console.WriteLine("Input not an integer. Please try again");
help();
pid = 0;
}
try
{
// Get the process object for the pid input
Process proc = Process.GetProcessById(pid);
// Get the collection of threads for the process
ProcessThreadCollection threads = proc.Threads;
// List the threads to console
foreach (ProcessThread thread in threads)
{
// List the thread start address in hex format, the thread state, and the thread's base priority
Console.WriteLine("TID: {0} Start Address: 0x{1} Thread State: {2} Base Priority: {3}", thread.Id, thread.StartAddress.ToString("X"), thread.ThreadState, thread.BasePriority);
}
}
// If it fails call the help() function to return to the menu and alert the user to the failure
catch(Exception ex)
{
Console.WriteLine("No Process Found with that Process ID. \nError: {0}", ex);
help();
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from antman1p
with GNU General Public License v3.0
from antman1p
public static void ModList(string pidString)
{
int pid;
// Ensure the input is an integer
try
{
pid = Convert.ToInt32(pidString);
}
// If not got to the help and alert the user
catch (Exception ex)
{
Console.WriteLine("Input not an integer. Please try again");
help();
pid = 0;
}
try
{
// Get the process requested by the user pid input
Process process = Process.GetProcessById(pid);
ProcessModule procMod;
// Get the module collection of the process
ProcessModuleCollection processModuleColl = process.Modules;
// For each module in the collection write the modules to console
for ( int i =0; i < processModuleColl.Count; i++)
{
procMod = processModuleColl[i];
// Write the module name and base address in hex
Console.WriteLine("File Name: {0} Base Address: 0x{1}", procMod.FileName, procMod.BaseAddress.ToString("X"));
}
}
// If it fails alert the user and go to the help
catch(Exception ex)
{
Console.WriteLine("No Process Found with that Process ID. \nError: {0}", ex);
help();
}
}
19
Source : FastNativeDetour.cs
with GNU Lesser General Public License v2.1
from BepInEx
with GNU Lesser General Public License v2.1
from BepInEx
public void Apply(ManualLogSource debuggerLogSource)
{
if (IsApplied)
return;
DetourHelper.Native.MakeWritable(OriginalFunctionPtr, 32);
if (debuggerLogSource != null)
{
debuggerLogSource
.LogDebug($"Detouring 0x{OriginalFunctionPtr.ToString("X")} -> 0x{DetourFunctionPtr.ToString("X")}");
debuggerLogSource.LogDebug("Original (32) asm");
DetourGenerator.Disreplacedemble(debuggerLogSource, OriginalFunctionPtr, 32);
}
var arch = IntPtr.Size == 8 ? Architecture.X64 : Architecture.X86;
GenerateTrampolineInner(out var trampolineLength, out var jmpLength);
DetourGenerator.ApplyDetour(OriginalFunctionPtr, DetourFunctionPtr, arch, trampolineLength - jmpLength);
if (debuggerLogSource != null)
{
debuggerLogSource.LogDebug($"Trampoline allocation: 0x{TrampolinePtr.ToString("X")}");
debuggerLogSource.LogDebug("Modified (32) asm");
DetourGenerator.Disreplacedemble(debuggerLogSource, OriginalFunctionPtr, 32);
debuggerLogSource.LogDebug($"Trampoline ({trampolineLength}) asm");
DetourGenerator.Disreplacedemble(debuggerLogSource, TrampolinePtr, trampolineLength);
}
DetourHelper.Native.MakeExecutable(OriginalFunctionPtr, 32);
IsApplied = true;
}
19
Source : Patcher.cs
with MIT License
from betenner
with MIT License
from betenner
private static void ApplyAllPatches(IntPtr processHandle, IntPtr baseAddress)
{
// NOTE: you can make a 'patches.txt' file, using the format '0x1234:9090' where 0x1234 indicates the offset (game.exe+0x1234) and 9090 indicates the patch value (nop nop)
string patchesContent = "";
if (File.Exists("patches.txt"))
patchesContent = File.ReadAllText("patches.txt");
if (patchesContent == "")
{
Program.ConsolePrint("WARNING: Not patches are beeing loaded. (If this is unexpected, double check your 'patches.txt' file!)", ConsoleColor.Yellow);
return;
}
string[] split = patchesContent.Split('\n');
int[] addr = new int[split.Length];
byte[][] patch = new byte[split.Length][];
// init arrays
// NOTE: limiting the amount of bytes to patch to prevent malicous abuse!
int bytePatchCount = 0;
for (int i = 0; i < split.Length; i++)
{
string[] data = split[i].Split(':');
if (data.Length < 2)
continue; // probs empty line
addr[i] = Convert.ToInt32(data[0], 0x10);
if (addr[i] == 0)
continue;
if (data[1][0] == '+')
{
// offset patch
string offset = data[1].Substring(1);
//byte[] buf = new byte[offset.Length / 2]; // amount of bytes in patch len?
byte[] buf = new byte[8]; // qword
if (!ReadProcessMemory(processHandle, IntPtr.Add(baseAddress, addr[i]), buf, buf.Length, out _))
{
Program.ConsolePrint("Error, failed read patch location!", ConsoleColor.Yellow);
continue; // non critical, just skip
}
patch[i] = BitConverter.GetBytes(BitConverter.ToInt64(buf, 0) + Convert.ToInt64(offset, 0x10));
}
else
{
// normal patch
patch[i] = new byte[data[1].Length / 2];
for (int j = 0; j < patch[i].Length; j++)
patch[i][j] = Convert.ToByte(data[1].Substring(j * 2, 2), 0x10);
}
}
// patch arrays
for (int i = 0; i < split.Length; i++)
{
if (addr[i] == 0)
continue;
if (patch[i] == null)
{
Program.ConsolePrint($"Invalid patch at line {i + 1}!", ConsoleColor.Yellow);
continue;
}
bytePatchCount += patch.Length;
if(bytePatchCount > 200) // NOTE: this is to prevent people from inject asm malware payloads using the patches.txt feature
{
Program.ConsolePrint($"Patch 0x{(baseAddress + addr[i]).ToString("X8")} reject, maximum patch sized reached!", ConsoleColor.Red);
continue;
}
Program.ConsolePrint($"Patching 0x{(baseAddress + addr[i]).ToString("X8")}");
if (!WriteProcessMemory(processHandle, IntPtr.Add(baseAddress, addr[i]), patch[i], patch[i].Length, out IntPtr bWritten1) || (int)bWritten1 != patch[i].Length)
Program.ConsolePrint($"Patch {i} failed!!", ConsoleColor.Red);
}
}
19
Source : Patcher.cs
with MIT License
from betenner
with MIT License
from betenner
private static void WaitForData(IntPtr processHandle, IntPtr baseAddress, int offset)
{
// now waiting for game to lock in inf loop
Program.ConsolePrint($"Waiting for data at 0x{(baseAddress + offset).ToString("X8")}...");
int count = 0;
while (count < 500) // 5000ms timeout
{
byte[] buff = new byte[3];
if (!ReadProcessMemory(processHandle, baseAddress + offset, buff, buff.Length, out _)) // pre
{
Program.ConsolePrint("Failed reading initial process memory", ConsoleColor.Red);
continue; // dont break?
}
if (buff[0] != 0x00 || buff[2] != 0x00)
break;
Thread.Sleep(10); // continue execution
count++;
}
}
19
Source : HandleBase.cs
with MIT License
from bibigone
with MIT License
from bibigone
public override string ToString()
=> GetType().Name + "#" + handle.ToString("X");
19
Source : LuaTable.cs
with MIT License
from bjfumac
with MIT License
from bjfumac
public override string ToString()
{
luaState.Push(this);
IntPtr p = luaState.LuaToPointer(-1);
luaState.LuaPop(1);
return string.Format("table:0x{0}", p.ToString("X"));
}
19
Source : Program.cs
with MIT License
from charanroaxz
with MIT License
from charanroaxz
private static void WaitForData(IntPtr processHandle, IntPtr baseAddress, int offset)
{
// now waiting for game to lock in inf loop
ConsolePrint($"Waiting for data at 0x{(baseAddress + offset).ToString("X8")}...");
int count = 0;
while (count < 500) // 5000ms timeout
{
byte[] buff = new byte[3];
if (!ReadProcessMemory(processHandle, baseAddress + offset, buff, buff.Length, out _)) // pre
{
ConsolePrint("Failed reading initial process memory", ConsoleColor.Red);
continue; // dont break?
}
if (buff[0] != 0x00 || buff[2] != 0x00)
break;
Thread.Sleep(10); // continue execution
count++;
}
}
19
Source : Program.cs
with MIT License
from charanroaxz
with MIT License
from charanroaxz
private static void ApplyAllPatches(IntPtr processHandle, IntPtr baseAddress)
{
// NOTE: you can make a 'patches.txt' file, using the format '0x1234:9090' where 0x1234 indicates the offset (game.exe+0x1234) and 9090 indicates the patch value (nop nop)
string patchesContent = "";
if (File.Exists("patches.txt"))
patchesContent = File.ReadAllText("patches.txt");
if (patchesContent == "")
{
ConsolePrint("WARNING: Not patches are beeing loaded. (If this is unexpected, double check your 'patches.txt' file!)", ConsoleColor.Yellow);
return;
}
string[] split = patchesContent.Split('\n');
int[] addr = new int[split.Length];
byte[][] patch = new byte[split.Length][];
// init arrays
for (int i = 0; i < split.Length; i++)
{
string[] data = split[i].Split(':');
if (data.Length < 2)
continue; // probs empty line
addr[i] = Convert.ToInt32(data[0], 0x10);
if (addr[i] == 0)
continue;
if (data[1][0] == '+')
{
// offset patch
string offset = data[1].Substring(1);
//byte[] buf = new byte[offset.Length / 2]; // amount of bytes in patch len?
byte[] buf = new byte[8]; // qword
if(!ReadProcessMemory(processHandle, IntPtr.Add(baseAddress, addr[i]), buf, buf.Length, out _))
{
ConsolePrint("Error, failed read patch location!", ConsoleColor.Yellow);
continue; // non critical, just skip
}
patch[i] = BitConverter.GetBytes(BitConverter.ToInt64(buf, 0) + Convert.ToInt64(offset, 0x10));
}
else
{
// normal patch
patch[i] = new byte[data[1].Length / 2];
for (int j = 0; j < patch[i].Length; j++)
patch[i][j] = Convert.ToByte(data[1].Substring(j * 2, 2), 0x10);
}
}
// patch arrays
for (int i = 0; i < split.Length; i++)
{
if (addr[i] == 0)
continue;
if(patch[i] == null)
{
ConsolePrint($"Invalid patch at line {i+1}!", ConsoleColor.Yellow);
continue;
}
ConsolePrint($"Patching 0x{(baseAddress+addr[i]).ToString("X8")}");
if (!WriteProcessMemory(processHandle, IntPtr.Add(baseAddress, addr[i]), patch[i], patch[i].Length, out IntPtr bWritten1) || (int)bWritten1 != patch[i].Length)
ConsolePrint($"Patch {i} failed!!", ConsoleColor.Red);
}
}
19
Source : Patcher.cs
with MIT License
from Chryseus
with MIT License
from Chryseus
private static void ApplyAllPatches(IntPtr processHandle, IntPtr baseAddress)
{
// NOTE: you can make a 'patches.txt' file, using the format '0x1234:9090' where 0x1234 indicates the offset (game.exe+0x1234) and 9090 indicates the patch value (nop nop)
string patchesContent = "";
if (File.Exists("patches.txt"))
patchesContent = File.ReadAllText("patches.txt");
if (patchesContent == "")
{
Program.ConsolePrint("WARNING: Not patches are beeing loaded. (If this is unexpected, double check your 'patches.txt' file!)", ConsoleColor.Yellow);
return;
}
string[] split = patchesContent.Split('\n');
int[] addr = new int[split.Length];
byte[][] patch = new byte[split.Length][];
// init arrays
// NOTE: limiting the amount of bytes to patch to prevent malicous abuse!
int bytePatchCount = 0;
for (int i = 0; i < split.Length; i++)
{
string[] data = split[i].Split(':');
if (data.Length < 2)
continue; // probs empty line
addr[i] = Convert.ToInt32(data[0], 0x10);
if (addr[i] == 0)
continue;
if (data[1][0] == '+')
{
// offset patch
string offset = data[1].Substring(1);
//byte[] buf = new byte[offset.Length / 2]; // amount of bytes in patch len?
byte[] buf = new byte[8]; // qword
if (!ReadProcessMemory(processHandle, IntPtr.Add(baseAddress, addr[i]), buf, buf.Length, out _))
{
Program.ConsolePrint("Error, failed read patch location!", ConsoleColor.Yellow);
continue; // non critical, just skip
}
patch[i] = BitConverter.GetBytes(BitConverter.ToInt64(buf, 0) + Convert.ToInt64(offset, 0x10));
}
else
{
// normal patch
patch[i] = new byte[data[1].Length / 2];
for (int j = 0; j < patch[i].Length; j++)
patch[i][j] = Convert.ToByte(data[1].Substring(j * 2, 2), 0x10);
}
}
// patch arrays
for (int i = 0; i < split.Length; i++)
{
if (addr[i] == 0)
continue;
if (patch[i] == null)
{
Program.ConsolePrint($"Invalid patch at line {i + 1}!", ConsoleColor.Yellow);
continue;
}
bytePatchCount += patch.Length;
if (bytePatchCount > 200) // NOTE: this is to prevent people from inject asm malware payloads using the patches.txt feature
{
Program.ConsolePrint($"Patch 0x{(baseAddress + addr[i]).ToString("X8")} reject, maximum patch sized reached!", ConsoleColor.Red);
continue;
}
Program.ConsolePrint($"Patching 0x{(baseAddress + addr[i]).ToString("X8")}");
if (!WriteProcessMemory(processHandle, IntPtr.Add(baseAddress, addr[i]), patch[i], patch[i].Length, out IntPtr bWritten1) || (int)bWritten1 != patch[i].Length)
Program.ConsolePrint($"Patch {i} failed!!", ConsoleColor.Red);
}
}
19
Source : WeChatSDK.cs
with MIT License
from cixingguangming55555
with MIT License
from cixingguangming55555
public List<string> GetAllModulesBaseAddress(Process _wx) {
if (_wx == null) return null;
List<string> _modules = new List<string>();
foreach (ProcessModule _pm in _wx.Modules) {
_modules.Add(String.Format("模块名称:{0},模块基址:0x{1}", _pm.ModuleName, _pm.BaseAddress.ToString("x8").ToUpper()));
Trace.WriteLine(String.Format("模块名称:{0},模块基址:0x{1}", _pm.ModuleName, _pm.BaseAddress.ToString("x8").ToUpper()));
}
return _modules;
}
19
Source : Managed.cs
with MIT License
from Const-me
with MIT License
from Const-me
public static void addRef( IntPtr p )
{
lock( syncRoot )
{
var mo = managed.lookup( p )?.getTarget();
if( null != mo )
{
mo.callAddRef();
return;
}
}
throw new ApplicationException( $"Native COM pointer { p.ToString( "X" ) } is not on the cache" );
}
19
Source : InputsHelper.cs
with GNU Affero General Public License v3.0
from DelvUI
with GNU Affero General Public License v3.0
from DelvUI
private void HookWndProc()
{
ulong processId = (ulong)Process.GetCurrentProcess().Id;
IntPtr hWnd = IntPtr.Zero;
do
{
hWnd = FindWindowExW(IntPtr.Zero, hWnd, "FFXIVGAME", null);
if (hWnd == IntPtr.Zero) { return; }
ulong wndProcessId = 0;
GetWindowThreadProcessId(hWnd, ref wndProcessId);
if (wndProcessId == processId)
{
break;
}
} while (hWnd != IntPtr.Zero);
if (hWnd == IntPtr.Zero) { return; }
_wndHandle = hWnd;
_wndProcDelegate = WndProcDetour;
_wndProcPtr = Marshal.GetFunctionPointerForDelegate(_wndProcDelegate);
_imguiWndProcPtr = SetWindowLongPtr(hWnd, GWL_WNDPROC, _wndProcPtr);
PluginLog.Log("Hooking WndProc for window: " + hWnd.ToString("X"));
PluginLog.Log("Old WndProc: " + _imguiWndProcPtr.ToString("X"));
}
19
Source : Bridge.cs
with The Unlicense
from devunt
with The Unlicense
from devunt
public void WriteLine(object format, params object[] args)
{
if (format is IntPtr ptr)
{
format = ptr.ToString("X");
}
if (format is IEnumerable<byte> bytes)
{
format = BitConverter.ToString(bytes.ToArray()).Replace('-', ' ');
}
var datetime = DateTime.Now.ToString("HH:mm:ss");
var formatted = $"[{datetime}] {string.Format(format.ToString(), args)}";
#if DEBUG
Console.WriteLine(formatted);
#else
Logs.Add(formatted);
#endif
}
19
Source : AtomicPtr.cs
with MIT License
from Egodystonic
with MIT License
from Egodystonic
public override string ToString() => GetAsIntPtr().ToString("x");
19
Source : MainForm.cs
with MIT License
from fengberd
with MIT License
from fengberd
private void timer1_Tick(object sender, EventArgs e)
{
GameWindow = FindGame();
label1.Text = GameWindow.ToString("X");
if (GameWindow != IntPtr.Zero)
{
checkBox1.Checked = false;
}
}
19
Source : AsiInterface.cs
with GNU General Public License v3.0
from fr-Pursuit
with GNU General Public License v3.0
from fr-Pursuit
public static void FillCrashReport(StringBuilder report)
{
report.Append("Pointer to RetVal: " + returnedValue.ToString("X") + '\n');
report.Append("Last native called: " + nativeHash.ToString("X") + '\n');
}
19
Source : CQEventExport.cs
with Apache License 2.0
from Hellobaka
with Apache License 2.0
from Hellobaka
[DllExport (ExportName = "_eventGroupMsg", CallingConvention = CallingConvention.StdCall)]
public static int Event_eventGroupMsg (int subType, int msgId, long fromGroup, long fromQQ, string fromAnonymous, IntPtr msg, int font)
{
if (Event_eventGroupMsgHandler != null)
{
CQGroupMessageEventArgs args = new CQGroupMessageEventArgs (AppData.CQApi, AppData.CQLog, 2, 2, "群消息处理", "_eventGroupMsg", 30000, subType, msgId, fromGroup, fromQQ, fromAnonymous, msg.ToString(CQApi.DefaultEncoding), false);
Event_eventGroupMsgHandler (typeof (CQEventExport), args);
return (int)(args.Handler ? CQMessageHandler.Intercept : CQMessageHandler.Ignore);
}
return 0;
}
19
Source : CQEventExport.cs
with Apache License 2.0
from Hellobaka
with Apache License 2.0
from Hellobaka
[DllExport (ExportName = "_eventPrivateMsg", CallingConvention = CallingConvention.StdCall)]
public static int Event_eventPrivateMsg (int subType, int msgId, long fromQQ, IntPtr msg, int font)
{
if (Event_eventPrivateMsgHandler != null)
{
CQPrivateMessageEventArgs args = new CQPrivateMessageEventArgs (AppData.CQApi, AppData.CQLog, 1, 21, "私聊消息处理", "_eventPrivateMsg", 30000, subType, msgId, fromQQ, msg.ToString(CQApi.DefaultEncoding), false);
Event_eventPrivateMsgHandler (typeof (CQEventExport), args);
return (int)(args.Handler ? CQMessageHandler.Intercept : CQMessageHandler.Ignore);
}
return 0;
}
19
Source : LogOutput.cs
with MIT License
from Hitmasu
with MIT License
from Hitmasu
public static void WriteLogMemory(IntPtr address, int size)
{
byte[] buffer = new byte[size];
Marshal.Copy(address, buffer, 0, size);
StringBuilder sb = new StringBuilder();
sb.Append("--------------------");
for (int i = 0; i < size; i++)
{
if (i % 8 == 0)
{
sb.Append($"{Environment.NewLine}0x{(address + i).ToString("X2")} - ");
}
byte b = buffer[i];
sb.Append($"{b:X2} ");
}
sb.Append("\n--------------------");
Output.WriteLine(sb.ToString());
}
19
Source : DropDownMenuBase.cs
with GNU General Public License v3.0
from indiff
with GNU General Public License v3.0
from indiff
protected override void WndProc(ref Message m) {
try {
QMenuItem ownerItem;
if(!fRespondModKeys) {
base.WndProc(ref m);
return;
}
int wParam = (int)((long)m.WParam);
switch(m.Msg) {
case WM.KEYDOWN:
break;
case WM.KEYUP:
if(fOnceKeyDown && ((wParam == 0x10) || (wParam == 0x11))) {
bool flag2 = false;
foreach(QMenuItem item4 in lstQMIResponds.Where(item4 => item4.Selected)) {
if(item4.Enabled) {
Keys modifierKeys = ModifierKeys;
if(modifierKeys == Keys.Control) {
item4.ImageKey = "control";
}
else if(fEnableShiftKey && (modifierKeys == Keys.Shift)) {
item4.ImageKey = "shift";
}
else {
item4.RestoreOriginalImage(fChangeImageSelected, false);
}
lastKeyImageChangedItem = item4;
}
flag2 = true;
break;
}
ownerItem = OwnerItem as QMenuItem;
if(ownerItem != null) {
DropDownMenuBase owner = ownerItem.Owner as DropDownMenuBase;
if((owner != null) && owner.Visible) {
if(flag2) {
PInvoke.SendMessage(owner.Handle, 0x2a3, IntPtr.Zero, IntPtr.Zero);
}
else {
QTUtility2.SendCOPYDATASTRUCT(owner.Handle, (IntPtr)wParam, string.Empty, (IntPtr)1);
}
}
}
}
goto Label_07C2;
case WM.MOUSEMOVE:
goto Label_0562;
case WM.MOUSELEAVE:
goto Label_072E;
case WM.PAINT:
if(fSuspendPainting) {
PInvoke.ValidateRect(m.HWnd, IntPtr.Zero);
}
else {
base.WndProc(ref m);
}
return;
case WM.COPYDATA: {
COPYDATASTRUCT copydatastruct = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT));
ownerItem = GereplacedemAt(PointToClient(MousePosition)) as QMenuItem;
if(!(copydatastruct.dwData == IntPtr.Zero)) {
goto Label_04B6;
}
if(ownerItem == null) {
goto Label_0462;
}
Keys keys3 = ModifierKeys;
if((wParam == 0x11) && ((keys3 & Keys.Shift) != Keys.Shift)) {
ownerItem.ImageKey = "control";
}
else if((fEnableShiftKey && (wParam == 0x10)) && ((keys3 & Keys.Control) != Keys.Control)) {
ownerItem.ImageKey = "shift";
}
else {
ownerItem.RestoreOriginalImage(fChangeImageSelected, false);
}
lastKeyImageChangedItem = ownerItem;
goto Label_07C2;
}
default:
goto Label_07C2;
}
fOnceKeyDown = true;
if((((int)((long)m.LParam)) & 0x40000000) == 0) {
if((wParam == 0x10) || (wParam == 0x11)) {
bool flag = false;
foreach(QMenuItem item2 in lstQMIResponds.Where(item2 => item2.Selected)) {
if(item2.Enabled) {
Keys keys = ModifierKeys;
if((wParam == 0x11) && ((keys & Keys.Shift) != Keys.Shift)) {
item2.ImageKey = "control";
}
else if((fEnableShiftKey && (wParam == 0x10)) && ((keys & Keys.Control) != Keys.Control)) {
item2.ImageKey = "shift";
}
else {
item2.RestoreOriginalImage(fChangeImageSelected, false);
}
lastKeyImageChangedItem = item2;
}
flag = true;
break;
}
ownerItem = OwnerItem as QMenuItem;
if(ownerItem != null) {
DropDownMenuBase base2 = ownerItem.Owner as DropDownMenuBase;
if((base2 != null) && base2.Visible) {
if(flag) {
PInvoke.SendMessage(base2.Handle, 0x2a3, IntPtr.Zero, IntPtr.Zero);
}
else {
QTUtility2.SendCOPYDATASTRUCT(base2.Handle, (IntPtr)wParam, string.Empty, IntPtr.Zero);
}
}
}
}
else if((wParam == 13) && ((fEnableShiftKey && (ModifierKeys == Keys.Shift)) || (ModifierKeys == Keys.Control))) {
foreach(ToolStripItem item3 in Items) {
if(item3.Selected) {
if(item3.Enabled) {
OnItemClicked(new ToolStripItemClickedEventArgs(item3));
}
break;
}
}
}
}
goto Label_07C2;
Label_0462:
ownerItem = OwnerItem as QMenuItem;
if(ownerItem != null) {
DropDownMenuBase base4 = ownerItem.Owner as DropDownMenuBase;
if((base4 != null) && base4.Visible) {
QTUtility2.SendCOPYDATASTRUCT(base4.Handle, (IntPtr)wParam, string.Empty, IntPtr.Zero);
}
}
goto Label_07C2;
Label_04B6:
if(ownerItem != null) {
Keys keys4 = ModifierKeys;
if(keys4 == Keys.Control) {
ownerItem.ImageKey = "control";
}
else if(fEnableShiftKey && (keys4 == Keys.Shift)) {
ownerItem.ImageKey = "shift";
}
else {
ownerItem.RestoreOriginalImage(fChangeImageSelected, false);
}
lastKeyImageChangedItem = ownerItem;
}
else {
ownerItem = OwnerItem as QMenuItem;
if(ownerItem != null) {
DropDownMenuBase base5 = ownerItem.Owner as DropDownMenuBase;
if((base5 != null) && base5.Visible) {
QTUtility2.SendCOPYDATASTRUCT(base5.Handle, (IntPtr)wParam, string.Empty, (IntPtr)1);
}
}
}
goto Label_07C2;
Label_0562:
if((m.WParam == IntPtr.Zero) && (m.LParam == lparamPreviousMouseMove)) {
m.Result = IntPtr.Zero;
return;
}
lparamPreviousMouseMove = m.LParam;
if((!fEnableShiftKey || ((wParam & 4) != 4)) && (((wParam & 8) != 8) && !fChangeImageSelected)) {
goto Label_07C2;
}
ToolStripItem itemAt = GereplacedemAt(QTUtility2.PointFromLPARAM(m.LParam));
if(itemAt == null) {
base.WndProc(ref m);
return;
}
ownerItem = itemAt as QMenuItem;
if(!IsQmiResponds(ownerItem)) {
goto Label_06F8;
}
if(ownerItem == lastMouseActiveItem) {
goto Label_07C2;
}
if(lstQMIResponds.Count > 0x1c) {
fSuspendPainting = true;
}
SuspendLayout();
if(ownerItem.Enabled) {
switch(wParam) {
case 8:
ownerItem.ImageKey = "control";
goto Label_06AB;
case 4:
ownerItem.ImageKey = "shift";
goto Label_06AB;
}
if(((ownerItem.Genre == MenuGenre.Navigation) && (ownerItem.MenuItemArguments != null)) && (!ownerItem.MenuItemArguments.IsBack || (ownerItem.MenuItemArguments.Index != 0))) {
ownerItem.ImageKey = ownerItem.MenuItemArguments.IsBack ? "back" : "forward";
}
else {
ownerItem.RestoreOriginalImage();
}
}
Label_06AB:
if(lastMouseActiveItem != null) {
lastMouseActiveItem.RestoreOriginalImage();
}
if((ownerItem != lastKeyImageChangedItem) && (lastKeyImageChangedItem != null)) {
lastKeyImageChangedItem.RestoreOriginalImage();
lastKeyImageChangedItem = null;
}
lastMouseActiveItem = ownerItem;
fSuspendPainting = false;
ResumeLayout(false);
goto Label_07C2;
Label_06F8:
if(lastMouseActiveItem != null) {
lastMouseActiveItem.RestoreOriginalImage();
lastMouseActiveItem = null;
}
if(lastKeyImageChangedItem != null) {
lastKeyImageChangedItem.RestoreOriginalImage();
lastKeyImageChangedItem = null;
}
goto Label_07C2;
Label_072E:
ResetImageKeys();
lastMouseActiveItem = null;
}
catch(Exception exception) {
QTUtility2.MakeErrorLog(exception, "MSG:" + m.Msg.ToString("X") + ", WPARAM:" + m.WParam.ToString("X") + ", LPARAM:" + m.LParam.ToString("X"));
}
Label_07C2:
base.WndProc(ref m);
fSuspendPainting = false;
}
19
Source : API.cs
with MIT License
from Jerrylum
with MIT License
from Jerrylum
public static void SetTopMost(IntPtr hwnd, bool topmost, bool tryAdmin = true)
{
Console.WriteLine(hwnd.ToString("X") + " set to " + topmost + "; Current = " + GetForegroundWindow().ToString("X"));
//if (topmost)
// if (TopmostWindowsLog.IndexOf(hwnd) == -1)
// TopmostWindowsLog.Add(hwnd);
// else
// TopmostWindowsLog.Remove(hwnd);
SetWindowPos(hwnd, topmost ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
if (IsTopMost(hwnd) != topmost)
{
if (!IsAdministrator())
{
if (tryAdmin)
{
Process cureent = Process.GetCurrentProcess();
string exeName = cureent.MainModule.FileName;
ProcessStartInfo startInfo = new ProcessStartInfo(exeName)
{
Verb = "runas",
Arguments = String.Format("--autostart -{0} 0x{1}", (topmost ? "S" : "R"), hwnd.ToString("X"))
};
try
{
Process.Start(startInfo);
Shutdown();
}
catch
{
Console.WriteLine("User cancel permission upgrade");
}
}
}
else
{
SystemSounds.Asterisk.Play(); // Failed to set top most
}
}
if (Program.OptionsForm != null)
Program.OptionsForm.UpdateNotifyIcon();
}
19
Source : CQEventExport.cs
with Apache License 2.0
from Jie2GG
with Apache License 2.0
from Jie2GG
[DllExport (ExportName = "_eventRequest_AddGroup", CallingConvention = CallingConvention.StdCall)]
public static int Event_eventRequest_AddGroup (int subType, int sendTime, long fromGroup, long fromQQ, IntPtr msg, string responseFlag)
{
if (Event_eventRequest_AddGroupHandler != null)
{
CQGroupAddRequestEventArgs args = new CQGroupAddRequestEventArgs (AppData.CQApi, AppData.CQLog, 12, 302, "群添加请求处理", "_eventRequest_AddGroup", 30000, subType, sendTime, fromGroup, fromQQ, msg.ToString (CQApi.DefaultEncoding), responseFlag);
Event_eventRequest_AddGroupHandler (typeof (CQEventExport), args);
return (int)(args.Handler ? CQMessageHandler.Intercept : CQMessageHandler.Ignore);
}
return 0;
}
19
Source : CQEventExport.cs
with Apache License 2.0
from Jie2GG
with Apache License 2.0
from Jie2GG
[DllExport (ExportName = "_eventRequest_AddFriend", CallingConvention = CallingConvention.StdCall)]
public static int Event_eventRequest_AddFriend (int subType, int sendTime, long fromQQ, IntPtr msg, string responseFlag)
{
if (Event_eventRequest_AddFriendHandler != null)
{
CQFriendAddRequestEventArgs args = new CQFriendAddRequestEventArgs (AppData.CQApi, AppData.CQLog, 11, 301, "好友添加请求处理", "_eventRequest_AddFriend", 30000, subType, sendTime, fromQQ, msg.ToString (CQApi.DefaultEncoding), responseFlag);
Event_eventRequest_AddFriendHandler (typeof (CQEventExport), args);
return (int)(args.Handler ? CQMessageHandler.Intercept : CQMessageHandler.Ignore);
}
return 0;
}
19
Source : CQEventExport.cs
with Apache License 2.0
from Jie2GG
with Apache License 2.0
from Jie2GG
[DllExport (ExportName = "_eventDiscussMsg", CallingConvention = CallingConvention.StdCall)]
public static int Event_eventDiscussMsg (int subType, int msgId, long fromNative, long fromQQ, IntPtr msg, int font)
{
if (Event_eventDiscussMsgHandler != null)
{
CQDiscussMessageEventArgs args = new CQDiscussMessageEventArgs (AppData.CQApi, AppData.CQLog, 3, 4, "讨论组消息处理", "_eventDiscussMsg", 30000, subType, msgId, fromNative, fromQQ, msg.ToString(CQApi.DefaultEncoding), false);
Event_eventDiscussMsgHandler (typeof (CQEventExport), args);
return (int)(args.Handler ? CQMessageHandler.Intercept : CQMessageHandler.Ignore);
}
return 0;
}
19
Source : MainSpider.cs
with GNU General Public License v3.0
from Jiiks
with GNU General Public License v3.0
from Jiiks
private void BtnSpider_Click(object sender, EventArgs e) {
if (!_spiderInitialized) InitializeSpider();
_inventory.Clear();
var sekiro = Utils.Sekiro();
if (sekiro == null) return;
var emptyItem = new SekiroItem() {
Id1 = 0,
Id2 = 0xFFFFFFFF,
Quanreplacedy = 0,
Garbage = 0
};
var itemCount = 0;
IntPtr address;
var remoteProc = RemoteProc.Instance();
if (remoteProc == null) return;
address = Defs.PointerByName("inventory").GetAddress(remoteProc);
var invStart = address.ToInt64();
var invEnd = invStart + 4800;
Diag.WriteLine($"Inv Start: {address.ToString("X")}");
var spiderIndex = 0;
while (address.ToInt64() < invEnd) {
var sekiroItem = remoteProc.Read<SekiroItem>(address);
address += 16;
var item = sekiroItem.ToItem();
item.SpiderIndex = spiderIndex;
spiderIndex++;
_inventory.Add(item);
if (sekiroItem.Equals(emptyItem)) continue;
itemCount++;
}
Diag.WriteLine($"Inv End: {address.ToString("X")}");
Diag.WriteLine($"Spidered {itemCount} items");
var currentRow = 0;
itemGrid.RowCount = itemCount;
foreach (var item in _inventory) {
if (item.Empty) continue;
itemGrid.CurrentCell = itemGrid.Rows[currentRow].Cells[0];
itemGrid.CurrentCell.Value = item.SpiderIndex;
itemGrid.CurrentCell = itemGrid.Rows[currentRow].Cells[1];
var cbox = (DataGridViewComboBoxCell)itemGrid.CurrentCell;
foreach (var defi in Defs.Items) {
cbox.Items.Add(defi.Name);
}
cbox.Items.Add("Unknown");
cbox.Value = item.Name;
itemGrid.CurrentCell = itemGrid.Rows[currentRow].Cells[2];
itemGrid.CurrentCell.Value = item.SekiroItem.Quanreplacedy;
itemGrid.CurrentCell = itemGrid.Rows[currentRow].Cells[3];
itemGrid.CurrentCell.Value = "Not Implemented";
currentRow++;
}
}
19
Source : HookLibrary.cs
with MIT License
from joergkrause
with MIT License
from joergkrause
private string GetModulePath(IntPtr handle)
{
return Path.Combine(
Path.GetTempPath(),
String.Concat(GetType().Name, "-0x", handle.ToString("x8"), ".dll")
);
}
19
Source : MemoryGpioConnectionDriver.cs
with MIT License
from JTrotta
with MIT License
from JTrotta
public bool Read(ProcessorPin pin)
{
int shift, offset;
IntPtr pinGroupAddress;
if ((int)pin < 32)
{
offset = Math.DivRem((int)pin, 32, out shift);
pinGroupAddress = gpioAddress + (int)(OP.BCM2835_GPLEV0 + offset);
}
else
{
offset = Math.DivRem((int)pin - 32, 32, out shift);
pinGroupAddress = gpioAddress + (int)(OP.BCM2835_GPLEV1 + offset);
}
var value = SafeReadUInt32(pinGroupAddress);
Console.WriteLine($"Reading Done GPIO offset:{offset} pinGroupAddress:{pinGroupAddress.ToString("X8")} shift: {shift} value:{value}");
return (value & ((uint)1 << shift)) != 0;
}
19
Source : Program.cs
with MIT License
from lolp1
with MIT License
from lolp1
static void Main(string[] args)
{
Console.WriteLine("Please enter the process name with out extension (for example, if process name is game.exe enter just game) and press Enter.");
var processName = Console.ReadLine();
var processCollection = System.Diagnostics.Process.GetProcessesByName(processName);
if(processCollection == null || !processCollection.Any())
{
Console.WriteLine($"No process found by the name: {processName} exit the console (hit enter or the X) and try again");
Console.ReadLine();
return;
}
var process = processCollection.FirstOrDefault();
if(process == null)
{
Console.WriteLine($"No process found by the name: {processName} or is now invalid, exit the console (hit enter or the X) and try again");
Console.ReadLine();
return;
}
var dxDevice = new Dirext3D(process);
var dxVersion = dxDevice.UsingDirectX11 ? "Directx11" : "Directx9";
var functionToHook = dxDevice.UsingDirectX11 ? "public delegate int DxgiSwapChainPresentDelegate(IntPtr swapChainPtr, int syncInterval, int flags)" : "public delegate int Direct3D9EndScene(IntPtr device)";
var processSize = IntPtr.Size == 4 ? "x86" : "x64";
Console.WriteLine($"DirectX version: {dxVersion}");
Console.WriteLine($"Process architecture: {processSize}");
Console.WriteLine($"Function to hook: {functionToHook}");
var rebased = new IntPtr(dxDevice.HookAddress.ToInt64() - process.MainModule.BaseAddress.ToInt64());
Console.WriteLine($"ImageBase + offset hook address= {dxDevice.HookAddress.ToString("X")}");
Console.WriteLine($"Offset hook address: = {rebased.ToString("X")}");
Console.WriteLine("Hit enter to exit or close the console");
Console.ReadLine();
}
19
Source : Tools.cs
with Apache License 2.0
from marcosecchi
with Apache License 2.0
from marcosecchi
public static string sprintf(string Format, params object[] Parameters)
{
#region Variables
StringBuilder f = new StringBuilder();
//Regex r = new Regex( @"\%(\d*\$)?([\'\#\-\+ ]*)(\d*)(?:\.(\d+))?([hl])?([dioxXucsfeEgGpn%])" );
//"%[parameter][flags][width][.precision][length]type"
Match m = null;
string w = String.Empty;
int defaultParamIx = 0;
int paramIx;
object o = null;
bool flagLeft2Right = false;
bool flagAlternate = false;
bool flagPositiveSign = false;
bool flagPositiveSpace = false;
bool flagZeroPadding = false;
bool flagGroupThousands = false;
int fieldLength = 0;
int fieldPrecision = 0;
char shortLongIndicator = '\0';
char formatSpecifier = '\0';
char paddingCharacter = ' ';
#endregion
// find all format parameters in format string
f.Append(Format);
m = r.Match(f.ToString());
while (m.Success)
{
#region parameter index
paramIx = defaultParamIx;
if (m.Groups[1] != null && m.Groups[1].Value.Length > 0)
{
string val = m.Groups[1].Value.Substring(0, m.Groups[1].Value.Length - 1);
paramIx = Convert.ToInt32(val) - 1;
};
#endregion
#region format flags
// extract format flags
flagAlternate = false;
flagLeft2Right = false;
flagPositiveSign = false;
flagPositiveSpace = false;
flagZeroPadding = false;
flagGroupThousands = false;
if (m.Groups[2] != null && m.Groups[2].Value.Length > 0)
{
string flags = m.Groups[2].Value;
flagAlternate = (flags.IndexOf('#') >= 0);
flagLeft2Right = (flags.IndexOf('-') >= 0);
flagPositiveSign = (flags.IndexOf('+') >= 0);
flagPositiveSpace = (flags.IndexOf(' ') >= 0);
flagGroupThousands = (flags.IndexOf('\'') >= 0);
// positive + indicator overrides a
// positive space character
if (flagPositiveSign && flagPositiveSpace)
flagPositiveSpace = false;
}
#endregion
#region field length
// extract field length and
// pading character
paddingCharacter = ' ';
fieldLength = int.MinValue;
if (m.Groups[3] != null && m.Groups[3].Value.Length > 0)
{
fieldLength = Convert.ToInt32(m.Groups[3].Value);
flagZeroPadding = (m.Groups[3].Value[0] == '0');
}
#endregion
if (flagZeroPadding)
paddingCharacter = '0';
// left2right allignment overrides zero padding
if (flagLeft2Right && flagZeroPadding)
{
flagZeroPadding = false;
paddingCharacter = ' ';
}
#region field precision
// extract field precision
fieldPrecision = int.MinValue;
if (m.Groups[4] != null && m.Groups[4].Value.Length > 0)
fieldPrecision = Convert.ToInt32(m.Groups[4].Value);
#endregion
#region short / long indicator
// extract short / long indicator
shortLongIndicator = Char.MinValue;
if (m.Groups[5] != null && m.Groups[5].Value.Length > 0)
shortLongIndicator = m.Groups[5].Value[0];
#endregion
#region format specifier
// extract format
formatSpecifier = Char.MinValue;
if (m.Groups[6] != null && m.Groups[6].Value.Length > 0)
formatSpecifier = m.Groups[6].Value[0];
#endregion
// default precision is 6 digits if none is specified except
if (fieldPrecision == int.MinValue &&
formatSpecifier != 's' &&
formatSpecifier != 'c' &&
Char.ToUpper(formatSpecifier) != 'X' &&
formatSpecifier != 'o')
fieldPrecision = 6;
#region get next value parameter
// get next value parameter and convert value parameter depending on short / long indicator
if (Parameters == null || paramIx >= Parameters.Length)
o = null;
else
{
o = Parameters[paramIx];
if (shortLongIndicator == 'h')
{
if (o is int)
o = (short)((int)o);
else if (o is long)
o = (short)((long)o);
else if (o is uint)
o = (ushort)((uint)o);
else if (o is ulong)
o = (ushort)((ulong)o);
}
else if (shortLongIndicator == 'l')
{
if (o is short)
o = (long)((short)o);
else if (o is int)
o = (long)((int)o);
else if (o is ushort)
o = (ulong)((ushort)o);
else if (o is uint)
o = (ulong)((uint)o);
}
}
#endregion
// convert value parameters to a string depending on the formatSpecifier
w = String.Empty;
switch (formatSpecifier)
{
#region % - character
case '%': // % character
w = "%";
break;
#endregion
#region d - integer
case 'd': // integer
w = FormatNumber((flagGroupThousands ? "n" : "d"), flagAlternate,
fieldLength, int.MinValue, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o);
defaultParamIx++;
break;
#endregion
#region i - integer
case 'i': // integer
goto case 'd';
#endregion
#region o - octal integer
case 'o': // octal integer - no leading zero
w = FormatOct("o", flagAlternate,
fieldLength, int.MinValue, flagLeft2Right,
paddingCharacter, o);
defaultParamIx++;
break;
#endregion
#region x - hex integer
case 'x': // hex integer - no leading zero
w = FormatHex("x", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
paddingCharacter, o);
defaultParamIx++;
break;
#endregion
#region X - hex integer
case 'X': // same as x but with capital hex characters
w = FormatHex("X", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
paddingCharacter, o);
defaultParamIx++;
break;
#endregion
#region u - unsigned integer
case 'u': // unsigned integer
w = FormatNumber((flagGroupThousands ? "n" : "d"), flagAlternate,
fieldLength, int.MinValue, flagLeft2Right,
false, false,
paddingCharacter, ToUnsigned(o));
defaultParamIx++;
break;
#endregion
#region c - character
case 'c': // character
if (IsNumericType(o))
w = Convert.ToChar(o).ToString();
else if (o is char)
w = ((char)o).ToString();
else if (o is string && ((string)o).Length > 0)
w = ((string)o)[0].ToString();
defaultParamIx++;
break;
#endregion
#region s - string
case 's': // string
//string t = "{0" + ( fieldLength != int.MinValue ? "," + ( flagLeft2Right ? "-" : String.Empty ) + fieldLength.ToString() : String.Empty ) + ":s}";
w = o.ToString();
if (fieldPrecision >= 0)
w = w.Substring(0, fieldPrecision);
if (fieldLength != int.MinValue)
if (flagLeft2Right)
w = w.PadRight(fieldLength, paddingCharacter);
else
w = w.PadLeft(fieldLength, paddingCharacter);
defaultParamIx++;
break;
#endregion
#region f - double number
case 'f': // double
w = FormatNumber((flagGroupThousands ? "n" : "f"), flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o);
defaultParamIx++;
break;
#endregion
#region e - exponent number
case 'e': // double / exponent
w = FormatNumber("e", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o);
defaultParamIx++;
break;
#endregion
#region E - exponent number
case 'E': // double / exponent
w = FormatNumber("E", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o);
defaultParamIx++;
break;
#endregion
#region g - general number
case 'g': // double / exponent
w = FormatNumber("g", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o);
defaultParamIx++;
break;
#endregion
#region G - general number
case 'G': // double / exponent
w = FormatNumber("G", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o);
defaultParamIx++;
break;
#endregion
#region p - pointer
case 'p': // pointer
if (o is IntPtr)
#if PCL || ENABLE_DOTNET
w = ( (IntPtr)o ).ToString();
#else
w = "0x" + ((IntPtr)o).ToString("x");
#endif
defaultParamIx++;
break;
#endregion
#region n - number of processed chars so far
case 'n': // number of characters so far
w = FormatNumber("d", flagAlternate,
fieldLength, int.MinValue, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, m.Index);
break;
#endregion
default:
w = String.Empty;
defaultParamIx++;
break;
}
// replace format parameter with parameter value
// and start searching for the next format parameter
// AFTER the position of the current inserted value
// to prohibit recursive matches if the value also
// includes a format specifier
f.Remove(m.Index, m.Length);
f.Insert(m.Index, w);
m = r.Match(f.ToString(), m.Index + w.Length);
}
return f.ToString();
}
19
Source : Program.cs
with The Unlicense
from marcussacana
with The Unlicense
from marcussacana
public static void SampleMAlloc(RemoteControl Control, Process Process) {
//Remove the "SUSPENDED" state of the process
Control.ResumeProcess();
const string Message = "This is a test of the auto memory allocator of the RemoteProcess library, This string is big as try to fill the 10mb of space with less calls... Well, let's see how this will works, are you ready?";
string Parse = Process.Is64Bits() ? "X16" : "X8";
byte[] Data = Encoding.Unicode.GetBytes(Message + "\x0");
Console.WriteLine("Writing");
//Allocate 100x
IntPtr[] Address = new IntPtr[100];
for (uint i = 0; i < Address.Length; i++)
Address[i] = Process.MAlloc(Data);
Console.WriteLine("Validating...");
for (uint i = 0; i < Address.Length; i++) {
string Content = Process.ReadString(Address[i], true);
if (Content != Message)
Console.WriteLine("Validation Failed at 0x" + Address[i].ToString(Parse));
}
Console.WriteLine("Disposing...");
//Release all 100 address
for (uint i = 0; i < Address.Length; i++)
Process.MFree(Address[i]);
Console.WriteLine("Finished");
}
19
Source : Loader.cs
with MIT License
from med0x2e
with MIT License
from med0x2e
public static void rexec(int pid, byte[] scode)
{
int PID = pid;
byte[] payload = scode;
Console.WriteLine("[+]: Opening Remote Process PID: {0}", PID);
IntPtr hProc = OpenProcess(0x001F0FFF, false, PID);
if (hProc == IntPtr.Zero)
{
Console.WriteLine("OpenProcess Failed. Error: {0}", GetLastError());
return;
}
IntPtr mem;
mem = VirtualAllocEx(hProc, IntPtr.Zero, (uint)payload.Length, 0x1000, 0x40);
Console.WriteLine("[+]: Memory allocated at 0x{0}", mem.ToString("X"));
if (mem == IntPtr.Zero)
{
Console.WriteLine("VirtualAllocEx Failed. Error: {0}", GetLastError());
return;
}
if (!WriteProcessMemory(hProc, mem, payload, payload.Length, out var bytes))
{
Console.WriteLine("WriteProcessMemory Failed. Error: {0}", GetLastError());
return;
}
IntPtr hThread;
hThread = CreateRemoteThread(hProc, IntPtr.Zero, 0, mem, IntPtr.Zero, 0, out var ThreadID);
if (hThread == IntPtr.Zero)
{
Console.WriteLine("CreateRemoteThread Failed. Error: {0}", GetLastError());
return;
}
Console.WriteLine("[+]: Thread located at 0x{0}", hThread.ToString("X"));
Console.WriteLine("[*]: Payload executed in the context of PID: {0}", PID);
WaitForSingleObject(hThread, 0xFFFFFFFF);
Console.WriteLine("Done.");
}
19
Source : MemoryScanner.cs
with MIT License
from MgAl2O4
with MIT License
from MgAl2O4
private void InitMemoryRegions()
{
cachedProcessBase = (long)cachedProcess.MainModule.BaseAddress;
MemoryRegionInfo baseModuleInfo = new MemoryRegionInfo
{
BaseAddress = new IntPtr(cachedProcessBase),
Size = new IntPtr(cachedProcess.MainModule.ModuleMemorySize),
Type = MemoryRegionFlags.Executable | MemoryRegionFlags.Writeable | MemoryRegionFlags.MainModule,
};
memoryRegions.Add(baseModuleInfo);
Logger.WriteLine("base:0x{0} [{1}], size:0x{2}", baseModuleInfo.BaseAddress.ToString("x"), cachedProcess.MainModule.ModuleName, baseModuleInfo.Size.ToString("x"));
}
19
Source : MemoryScanner.cs
with MIT License
from MgAl2O4
with MIT License
from MgAl2O4
public void CacheMemoryRegions()
{
memoryRegions.Clear();
InitMemoryRegions();
MemoryProtectionFlags MemFlagsExecutable =
MemoryProtectionFlags.PAGE_EXECUTE |
MemoryProtectionFlags.PAGE_EXECUTE_READ |
MemoryProtectionFlags.PAGE_EXECUTE_READWRITE |
MemoryProtectionFlags.PAGE_EXECUTE_WRITECOPY;
MemoryProtectionFlags MemFlagsWriteable =
MemoryProtectionFlags.PAGE_EXECUTE_READWRITE |
MemoryProtectionFlags.PAGE_EXECUTE_WRITECOPY |
MemoryProtectionFlags.PAGE_READWRITE |
MemoryProtectionFlags.PAGE_WRITECOPY;
int regionInfoSize = Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION));
for (long scanAddress = 0; scanAddress < Int64.MaxValue;)
{
MEMORY_BASIC_INFORMATION regionInfo;
int result = VirtualQueryEx(cachedProcessHandle, (IntPtr)scanAddress, out regionInfo, (uint)regionInfoSize);
if (result != regionInfoSize)
{
break;
}
bool bIsCommited = (regionInfo.State & MemoryStateFlags.MEM_COMMIT) != 0;
bool bIsGuarded = (regionInfo.Protect & MemoryProtectionFlags.PAGE_GUARD) != 0;
bool bIsWritebale = (regionInfo.Protect & MemFlagsWriteable) != 0;
bool bIsExecutable = (regionInfo.Protect & MemFlagsExecutable) != 0;
bool bShouldCacheRegion = bIsCommited && !bIsGuarded && (bIsWritebale || bIsExecutable);
Logger.WriteLine("scan:0x{0}, size:0x{1}, state:[{2}], protect:[{3}], type:0x{4} => {5}",
scanAddress.ToString("x"), regionInfo.RegionSize.ToString("x"), regionInfo.State, regionInfo.Protect, regionInfo.Type.ToString("x"),
bShouldCacheRegion ? "CACHE" : "meh");
if (bShouldCacheRegion)
{
MemoryRegionFlags storeType = (bIsWritebale ? MemoryRegionFlags.Writeable : 0) | (bIsExecutable ? MemoryRegionFlags.Executable : 0);
MemoryRegionInfo storeInfo = new MemoryRegionInfo
{
BaseAddress = regionInfo.BaseAddress,
Size = regionInfo.RegionSize,
Type = storeType,
};
memoryRegions.Add(storeInfo);
}
scanAddress = (long)regionInfo.BaseAddress + (long)regionInfo.RegionSize;
}
}
19
Source : EliteBase.cs
with MIT License
from mhwlng
with MIT License
from mhwlng
public DirectInputKeyCode ConvertLocaleScanCode(DirectInputKeyCode scanCode)
{
//german
// http://kbdlayout.info/KBDGR/shiftstates+scancodes/base
// french
// http://kbdlayout.info/kbdfr/shiftstates+scancodes/base
// usa
// http://kbdlayout.info/kbdusx/shiftstates+scancodes/base
if (Program.Binding[BindingType.OnFoot].KeyboardLayout != "en-US")
{
Logger.Instance.LogMessage(TracingLevel.INFO, scanCode.ToString() + " " + ((ushort)scanCode).ToString("X"));
int lpdwProcessId;
IntPtr hWnd = GetForegroundWindow();
int WinThreadProcId = GetWindowThreadProcessId(hWnd, out lpdwProcessId);
var hkl = GetKeyboardLayout(WinThreadProcId);
Logger.Instance.LogMessage(TracingLevel.INFO, ((long)hkl).ToString("X"));
//hkl = (IntPtr)67568647; // de-DE 4070407
// Maps the virtual scanCode to key code for the current locale
var virtualKeyCode = MapVirtualKeyEx((ushort)scanCode, 3, hkl);
if (virtualKeyCode > 0)
{
// map key code back to en-US scan code :
hkl = (IntPtr) 67699721; // en-US 4090409
var virtualScanCode = MapVirtualKeyEx((ushort) virtualKeyCode, 4, hkl) ;
if (virtualScanCode > 0)
{
Logger.Instance.LogMessage(TracingLevel.INFO,
"keycode " + virtualKeyCode.ToString("X") + " scancode " + virtualScanCode.ToString("X") +
" keyboard code " + hkl.ToString("X"));
return (DirectInputKeyCode) (virtualScanCode & 0xff); // only use low byte
}
}
}
return scanCode;
}
19
Source : FipHandler.cs
with MIT License
from mhwlng
with MIT License
from mhwlng
private void DeviceCallback(IntPtr device, bool added, IntPtr context)
{
try
{
//Called whenever a DirectOutput device is added or removed from the system.
App.Log.Info("DeviceCallback(): 0x" + device.ToString("x") + (added ? " Added" : " Removed"));
if (!IsFipDevice(device))
{
return;
}
if (!added && _fipPanels.Count == 0)
{
return;
}
var i = _fipPanels.Count - 1;
var found = false;
do
{
if (_fipPanels[i].FipDevicePointer == device)
{
found = true;
var fipPanel = _fipPanels[i];
if (!added)
{
fipPanel.Shutdown();
_fipPanels.Remove(fipPanel);
}
}
i--;
} while (i >= 0);
if (added && !found)
{
App.Log.Info("DeviceCallback() Spawning FipPanel. " + device);
var fipPanel = new FipPanel(device);
_fipPanels.Add(fipPanel);
fipPanel.Initalize();
}
}
catch (Exception ex)
{
App.Log.Error(ex);
}
}
19
Source : Win32.cs
with MIT License
from microsoft
with MIT License
from microsoft
public string NiceOutput()
{
string s = new String(' ',1);
s = "x="+x.ToString() + "\n";
s += "y=" + y.ToString() + "\n";
s += "id=" + id.ToString() + "\n";
s += "mask=0x" + mask.ToString("X") + "\n";
s += "flags=0x" + flags.ToString("X") + "\n";
s += "time=" + time.ToString() + "\n";
s += "contactX=" + contactX.ToString() + "\n";
s += "contactY=" + contactY.ToString() + "\n";
s += "wparam=0x" + wparam.ToString("X") + "\n";
s += "lparam=0x" + lparam.ToString("X") + "\n";
return s;
}
19
Source : PointerSize.cs
with GNU General Public License v3.0
from mrojkov
with GNU General Public License v3.0
from mrojkov
public string ToString(string format)
{
if (format == null)
return ToString();
return string.Format(CultureInfo.CurrentCulture, "{0}", _size.ToString(format));
}
19
Source : ApiHook.cs
with MIT License
from NewLifeX
with MIT License
from NewLifeX
unsafe private static void ReplaceMethod(IntPtr src, IntPtr dest)
{
XTrace.WriteLine("0x{0}=>0x{1}", src.ToString("x"), dest.ToString("x"));
//ShowMethod(src);
//ShowMethod(dest);
// 区分处理x86和x64
if (IntPtr.Size == 8)
{
var d = (ulong*)src.ToPointer();
*d = *((ulong*)dest.ToPointer());
}
else
{
var d = (uint*)src.ToPointer();
*d = *((uint*)dest.ToPointer());
}
}
19
Source : ApiHook.cs
with MIT License
from NewLifeX
with MIT License
from NewLifeX
private static void ShowMethod(IntPtr mt)
{
XTrace.WriteLine("ShowMethod: {0}", mt.ToString("x"));
var buf = new Byte[8];
Marshal.Copy(mt, buf, 0, buf.Length);
//XTrace.WriteLine(buf.ToHex("-"));
var ip = new IntPtr((Int64)buf.ToUInt64());
XTrace.WriteLine("{0}", ip.ToString("x"));
if (ip.ToInt64() <= 0x1000000 || ip.ToInt64() > 0x800000000000L) return;
buf = new Byte[32];
Marshal.Copy(ip, buf, 0, buf.Length);
XTrace.WriteLine(buf.ToHex("-"));
}
19
Source : NativeImports.cs
with MIT License
from oleg-shilo
with MIT License
from oleg-shilo
static string MessageHelper(IntPtr address, int countBytes)
{
return String.Format("Failed to read memory at 0x" + address.ToString("x") + " of " + countBytes + " bytes.");
}
19
Source : OverlayWindow.cs
with MIT License
from paissaheavyindustries
with MIT License
from paissaheavyindustries
public override string ToString()
{
return OverrideHelper.ToString(
"Handle", Handle.ToString("X"),
"IsInitialized", IsInitialized.ToString(),
"IsVisible", IsVisible.ToString(),
"IsTopmost", IsTopmost.ToString(),
"X", X.ToString(),
"Y", Y.ToString(),
"Width", Width.ToString(),
"Height", Height.ToString());
}
See More Examples