Here are the examples of the csharp api System.IntPtr.ToInt32() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
889 Examples
19
Source : NativeAPI.cs
with Apache License 2.0
from 1694439208
with Apache License 2.0
from 1694439208
public static void WriteMemoryValue(int baseAddress, string processName, int value)
{
try
{
//打开一个已存在的进程对象 0x1F0FFF 最高权限
IntPtr hProcess = OpenProcess(0x1F0FFF, false, GetPidByProcessName(processName));
//从指定内存中写入字节集数据
WriteProcessMemory(hProcess.ToInt32(), (IntPtr)baseAddress, BitConverter.GetBytes(value), 4, IntPtr.Zero.ToInt32());
//关闭操作
CloseHandle(hProcess);
}
catch { }
}
19
Source : Inline_Hook.cs
with Apache License 2.0
from 1694439208
with Apache License 2.0
from 1694439208
public static IntPtr InlineHook(int HookAddress, int Hooklen,
byte[] HookBytes0,int Callback,int CallbackOffset,
bool IsFront,int CallAddress,string name, Action<Methods.Register> func)
{
WeChetHook.DllcallBack dllcallBack = new WeChetHook.DllcallBack((de1, de2, ECX1, EAX1, EDX1, EBX1, ESP1, EBP1, ESI1, EDI1) => {
func(new Register
{
EAX = EAX1,
EBP = EBP1,
EBX = EBX1,
ECX = ECX1,
EDI = EDI1,
EDX = EDX1,
ESI = ESI1,
ESP = ESP1
});
});
int CallHandle = ComputeHash(name);
Methods.callBacks.Add(CallHandle, dllcallBack);
List<byte> byteSource1 = new List<byte>();
byteSource1.AddRange(new byte[] { 199, 134, 240, 2, 0, 0 });
byteSource1.AddRange(BitConverter.GetBytes(CallHandle));
byteSource1.AddRange(HookBytes0);
byte[] hookbytes = byteSource1.ToArray();
List<byte> byteSource = new List<byte>();
IntPtr ptr = NativeAPI.VirtualAlloc(0, 128, 4096, 64);
if (IsFront)
{
NativeAPI.WriteProcessMemory(-1, ptr, Add(new byte[] { 232 }, Inline_GetBuf(ptr, CallAddress)), 5, 0);
NativeAPI.WriteProcessMemory(-1, ptr + 5, hookbytes, hookbytes.Length, 0);
NativeAPI.WriteProcessMemory(-1, ptr + 5 + CallbackOffset, Inline_GetBuf(ptr + 5 + CallbackOffset - 1, Callback), 4, 0);
NativeAPI.WriteProcessMemory(-1, ptr + 5 + hookbytes.Length, Add(new byte[] { 233 }, Inline_GetBuf(ptr + 5 + HookBytes0.Length, HookAddress + Hooklen)), 5, 0);
}
else {
NativeAPI.WriteProcessMemory(-1, ptr, hookbytes, hookbytes.Length, 0);
NativeAPI.WriteProcessMemory(-1, ptr + CallbackOffset, Inline_GetBuf(ptr + CallbackOffset - 1, Callback), 4, 0);
NativeAPI.WriteProcessMemory(-1, ptr + hookbytes.Length,Add(new byte[] { 232 },Inline_GetBuf(ptr + hookbytes.Length, CallAddress)), Hooklen, 0);
NativeAPI.WriteProcessMemory(-1, ptr + Hooklen + hookbytes.Length, Add(new byte[] { 233 }, Inline_GetBuf(ptr + Hooklen + HookBytes0.Length, HookAddress + Hooklen)), 5, 0);
}
NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress), Add(new byte[] { 233 }, Inline_GetBuf(HookAddress, ptr.ToInt32())), 5, 0);
for (int i = 0; i < Hooklen - 5; i++)
{
byteSource.Add(144);
}
byte[] ByteFill = byteSource.ToArray();
NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress + 5), ByteFill, ByteFill.Length, 0);
return ptr;
}
19
Source : NativeAPI.cs
with Apache License 2.0
from 1694439208
with Apache License 2.0
from 1694439208
public static string ReadMemoryStrValue(int baseAddress,int len)
{
try
{
byte[] buffer = new byte[len];
//获取缓冲区地址
IntPtr byteAddress = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
//打开一个已存在的进程对象 0x1F0FFF 最高权限
//IntPtr hProcess = OpenProcess(0x1F0FFF, false, GetPidByProcessName(""));
//将制定内存中的值读入缓冲区
ReadProcessMemory(-1, (IntPtr)baseAddress, byteAddress, len, IntPtr.Zero.ToInt32());
//关闭操作
//CloseHandle(hProcess);
//从非托管内存中读取一个 32 位带符号整数。
return Encoding.Unicode.GetString(buffer);
}
catch
{
return "";
}
}
19
Source : Inline_Hook.cs
with Apache License 2.0
from 1694439208
with Apache License 2.0
from 1694439208
public static IntPtr InlineHook(int HookAddress, int Hooklen,
byte[] HookBytes0, int Callback, int CallbackOffset,string name, Action<Methods.Register> func)
{
WeChetHook.DllcallBack dllcallBack = new WeChetHook.DllcallBack((de1, de2, ECX1, EAX1, EDX1, EBX1, ESP1, EBP1, ESI1, EDI1) => {
//int ECX, int EAX, int EDX, int EBX, int ESP, int EBP, int ESI, int EDI
func(new Register
{
EAX = EAX1,
EBP = EBP1,
EBX = EBX1,
ECX = ECX1,
EDI = EDI1,
EDX = EDX1,
ESI = ESI1,
ESP = ESP1
});
});
int CallHandle = ComputeHash(name);
System.Windows.Forms.MessageBox.Show("CallHandle:" + CallHandle.ToString());
Methods.callBacks.Add(CallHandle, dllcallBack);
List<byte> byteSource1 = new List<byte>();
byteSource1.AddRange(new byte[] { 199, 134, 240, 2, 0, 0 });
byteSource1.AddRange(BitConverter.GetBytes(CallHandle));//把标识指针绑定到寄存器我觉得不靠谱但是目前没啥问题
byteSource1.AddRange(HookBytes0);
byte[] hookbytes = byteSource1.ToArray();
List<byte> byteSource = new List<byte>();
IntPtr ptr = NativeAPI.VirtualAlloc(0, 128, 4096, 64);
NativeAPI.WriteProcessMemory(-1, ptr, hookbytes, hookbytes.Length, 0);
NativeAPI.WriteProcessMemory(-1, ptr + CallbackOffset, Inline_GetBuf(ptr + CallbackOffset - 1, Callback), 4, 0);
NativeAPI.WriteProcessMemory(-1, ptr + hookbytes.Length, Add(new byte[] { 233 }, Inline_GetBuf(ptr + hookbytes.Length, HookAddress+ Hooklen)), 5, 0);
NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress), Add(new byte[] { 233 }, Inline_GetBuf(HookAddress, ptr.ToInt32())), 5, 0);
for (int i = 0; i < Hooklen - 5; i++)
{
byteSource.Add(144);
}
byte[] ByteFill = byteSource.ToArray();
NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress + 5), ByteFill, ByteFill.Length, 0);
return ptr;
}
19
Source : Inline_Hook.cs
with Apache License 2.0
from 1694439208
with Apache License 2.0
from 1694439208
public static byte[] Inline_GetBuf(IntPtr Address, int jmp)
{
return BitConverter.GetBytes(jmp - Address.ToInt32() - 5);
}
19
Source : NativeAPI.cs
with Apache License 2.0
from 1694439208
with Apache License 2.0
from 1694439208
public static int ReadMemoryValue(int baseAddress)
{
try
{
byte[] buffer = new byte[4];
//获取缓冲区地址
IntPtr byteAddress = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
//打开一个已存在的进程对象 0x1F0FFF 最高权限
//IntPtr hProcess = OpenProcess(0x1F0FFF, false, GetPidByProcessName(""));
//将制定内存中的值读入缓冲区
ReadProcessMemory(-1, (IntPtr)baseAddress, byteAddress, 4, IntPtr.Zero.ToInt32());
//关闭操作
//CloseHandle(hProcess);
//从非托管内存中读取一个 32 位带符号整数。
return Marshal.ReadInt32(byteAddress);
}
catch
{
return 0;
}
}
19
Source : NativeAPI.cs
with Apache License 2.0
from 1694439208
with Apache License 2.0
from 1694439208
public static int GetMethodPTR(Type type,string name) {
return type.GetMethod(name).MethodHandle.GetFunctionPointer().ToInt32();
}
19
Source : ProxySetting.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static bool SetProxy(string strProxy, string exceptions, int type)
{
InternetPerConnOptionList list = new InternetPerConnOptionList();
int optionCount = 1;
if (type == 1)
{
optionCount = 1;
}
else if (type == 2 || type == 4)
{
optionCount = Utils.IsNullOrEmpty(exceptions) ? 2 : 3;
}
int m_Int = (int)PerConnFlags.PROXY_TYPE_DIRECT;
PerConnOption m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
if (type == 2)
{
m_Int = (int)(PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY);
m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER;
}
else if (type == 4)
{
m_Int = (int)(PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_AUTO_PROXY_URL);
m_Option = PerConnOption.INTERNET_PER_CONN_AUTOCONFIG_URL;
}
//int optionCount = Utils.IsNullOrEmpty(strProxy) ? 1 : (Utils.IsNullOrEmpty(exceptions) ? 2 : 3);
InternetConnectionOption[] options = new InternetConnectionOption[optionCount];
// USE a proxy server ...
options[0].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
//options[0].m_Value.m_Int = (int)((optionCount < 2) ? PerConnFlags.PROXY_TYPE_DIRECT : (PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY));
options[0].m_Value.m_Int = m_Int;
// use THIS proxy server
if (optionCount > 1)
{
options[1].m_Option = m_Option;
options[1].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(strProxy);
// except for these addresses ...
if (optionCount > 2)
{
options[2].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPreplaced;
options[2].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(exceptions);
}
}
// default stuff
list.dwSize = Marshal.SizeOf(list);
list.szConnection = IntPtr.Zero;
list.dwOptionCount = options.Length;
list.dwOptionError = 0;
int optSize = Marshal.SizeOf(typeof(InternetConnectionOption));
// make a pointer out of all that ...
IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length);
// copy the array over into that spot in memory ...
for (int i = 0; i < options.Length; ++i)
{
if (Environment.Is64BitOperatingSystem)
{
IntPtr opt = new IntPtr(optionsPtr.ToInt64() + (i * optSize));
Marshal.StructureToPtr(options[i], opt, false);
}
else
{
IntPtr opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize));
Marshal.StructureToPtr(options[i], opt, false);
}
}
list.options = optionsPtr;
// and then make a pointer out of the whole list
IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((int)list.dwSize);
Marshal.StructureToPtr(list, ipcoListPtr, false);
// and finally, call the API method!
int returnvalue = NativeMethods.InternetSetOption(IntPtr.Zero,
InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION,
ipcoListPtr, list.dwSize) ? -1 : 0;
if (returnvalue == 0)
{ // get the error codes, they might be helpful
returnvalue = Marshal.GetLastWin32Error();
}
// FREE the data ASAP
Marshal.FreeCoTaskMem(optionsPtr);
Marshal.FreeCoTaskMem(ipcoListPtr);
if (returnvalue > 0)
{ // throw the error codes, they might be helpful
//throw new Win32Exception(Marshal.GetLastWin32Error());
}
return (returnvalue < 0);
}
19
Source : Helpers.cs
with MIT License
from 71
with MIT License
from 71
public static byte[] GetJmpBytes(IntPtr destination)
{
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.Arm:
{
// LDR PC, [PC, #-4]
// $addr
byte[] result = new byte[8];
result[0] = 0x04;
result[1] = 0xF0;
result[2] = 0x1F;
result[3] = 0xE5;
BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 4);
return result;
}
case Architecture.Arm64:
{
// LDR PC, [PC, #-4]
// $addr
byte[] result = new byte[12];
result[0] = 0x04;
result[1] = 0xF0;
result[2] = 0x1F;
result[3] = 0xE5;
BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 4);
return result;
}
case Architecture.X64:
{
// movabs rax,$addr
// jmp rax
byte[] result = new byte[12];
result[0] = 0x48;
result[1] = 0xB8;
result[10] = 0xFF;
result[11] = 0xE0;
BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 2);
return result;
}
case Architecture.X86:
{
// push $addr
// ret
byte[] result = new byte[6];
result[0] = 0x68;
result[5] = 0xC3;
BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 1);
return result;
}
default:
throw UnsupportedArchitecture;
}
}
19
Source : Ryder.Lightweight.cs
with MIT License
from 71
with MIT License
from 71
public static byte[] GetJmpBytes(IntPtr destination)
{
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.Arm:
{
// LDR PC, [PC, #-4]
// $addr
byte[] result = new byte[8];
result[0] = 0x04;
result[1] = 0xF0;
result[2] = 0x1F;
result[3] = 0xE5;
BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 4);
return result;
}
case Architecture.Arm64:
{
// LDR PC, [PC, #-4]
// $addr
byte[] result = new byte[12];
result[0] = 0x04;
result[1] = 0xF0;
result[2] = 0x1F;
result[3] = 0xE5;
BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 4);
return result;
}
case Architecture.X64:
{
// movabs rax,$addr
// jmp rax
byte[] result = new byte[12];
result[0] = 0x48;
result[1] = 0xB8;
result[10] = 0xFF;
result[11] = 0xE0;
BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 2);
return result;
}
case Architecture.X86:
{
// push $addr
// ret
byte[] result = new byte[6];
result[0] = 0x68;
result[5] = 0xC3;
BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 1);
return result;
}
default:
throw UnsupportedArchitecture;
}
}
19
Source : DMSkinComplexWindow.cs
with MIT License
from 944095635
with MIT License
from 944095635
IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
//WM_NCCALCSIZE
case (int)WindowMessages.WM_NCCALCSIZE:
//WmNCCalcSize(lParam);
ReWindow();
handled = true;
break;
///重绘 非客户区
case (int)WindowMessages.WM_NCPAINT:
// Here should all our painting occur, but...
handled = true;
return NativeConstants.TRUE;
case (int)WindowMessages.WM_NCACTIVATE:
// ... WM_NCACTIVATE does some painting directly
// without bothering with WM_NCPAINT ...
bool active = (wParam == NativeConstants.TRUE);
if (WindowState != WindowState.Minimized)
{
handled = true;
return NativeConstants.TRUE;
}
break;
//------------------
//if (wParam == (IntPtr)Win32.WM_TRUE)
//{
// handled = true;
//}
case (int)WindowMessages.WM_NCLBUTTONDOWN:
if (wParam.ToInt32() == (int)HitTest.HTCLOSE ||
wParam.ToInt32() == (int)HitTest.HTMAXBUTTON ||
wParam.ToInt32() == (int)HitTest.HTMINBUTTON ||
wParam.ToInt32() == (int)HitTest.HTHELP)
{
NativeMethods.SendMessage(Handle, (int)WindowMessages.WM_NCPAINT, IntPtr.Zero, IntPtr.Zero);
handled = true;
}
break;
case (int)WindowMessages.WM_NCUAHDRAWCAPTION:
case (int)WindowMessages.WM_NCUAHDRAWFRAME:
handled = true;
break;
//获取窗口的最大化最小化信息
//case (int)WindowMessages.WM_GETMINMAXINFO:
// WmGetMinMaxInfo(hwnd, lParam);
// handled = true;
// break;
//窗口拉伸 还有DPI BUG
//case (int)WindowMessages.WM_NCHITTEST:
// return WmNCHitTest(lParam, ref handled);
}
return IntPtr.Zero;
}
19
Source : DMSkinSimpleWindow.cs
with MIT License
from 944095635
with MIT License
from 944095635
IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
//获取窗口的最大化最小化信息
case (int)WindowMessages.WM_GETMINMAXINFO:
WmGetMinMaxInfo(hwnd, lParam);
handled = true;
break;
//case Win32.WM_NCHITTEST:
// return WmNCHitTest(lParam, ref handled);
case (int)WindowMessages.WM_SYSCOMMAND:
//if (wParam.ToInt32() == Win32.SC_MINIMIZE)//最小化消息
//{
//StoryboardHide();//执行最小化动画
//handled = true;
//}
if (wParam.ToInt32() == (int)SystemCommands.SC_RESTORE)//恢复消息
{
WindowRestore();//执行恢复动画
handled = true;
}
break;
//case Win32.WM_NCPAINT:
// break;
//case Win32.WM_NCCALCSIZE:
// handled = true;
// break;
//case Win32.WM_NCUAHDRAWCAPTION:
//case Win32.WM_NCUAHDRAWFRAME:
// handled = true;
// break;
//case Win32.WM_NCACTIVATE:
// if (wParam == (IntPtr)Win32.WM_TRUE)
// {
// handled = true;
// }
// break;
}
return IntPtr.Zero;
}
19
Source : DMSkinComplexWindow.cs
with MIT License
from 944095635
with MIT License
from 944095635
private IntPtr WmNCHitTest(IntPtr lParam, ref bool handled)
{
this.mousePoint.X = (int)(short)(lParam.ToInt32() & 0xFFFF);
this.mousePoint.Y = (int)(short)(lParam.ToInt32() >> 16);
if (ResizeMode == ResizeMode.CanResize || ResizeMode == ResizeMode.CanResizeWithGrip)
{
handled = true;
//if (Math.Abs(this.mousePoint.Y - this.Top) <= this.cornerWidth
// && Math.Abs(this.mousePoint.X - this.Left) <= this.cornerWidth)
//{ // 左上
// return new IntPtr((int)Win32.HitTest.HTTOPLEFT);
//}
//else if (Math.Abs(this.ActualHeight + this.Top - this.mousePoint.Y) <= this.cornerWidth
// && Math.Abs(this.mousePoint.X - this.Left) <= this.cornerWidth)
//{ // 左下
// return new IntPtr((int)Win32.HitTest.HTBOTTOMLEFT);
//}
//else if (Math.Abs(this.mousePoint.Y - this.Top) <= this.cornerWidth
// && Math.Abs(this.ActualWidth + this.Left - this.mousePoint.X) <= this.cornerWidth)
//{ //右上
// return new IntPtr((int)Win32.HitTest.HTTOPRIGHT);
//}
//else if (Math.Abs(this.mousePoint.X - this.Left) <= 30)
//{ // 左侧边框
// return new IntPtr((int)Win32.HitTest.HTLEFT);
//}
//else if (Math.Abs(this.mousePoint.Y - this.Top) <= 30)
//{ // 顶部
// return new IntPtr((int)Win32.HitTest.HTTOP);
//}
if (Math.Abs(this.ActualWidth + this.Left - this.mousePoint.X) <= this.cornerWidth
&& Math.Abs(this.ActualHeight + this.Top - this.mousePoint.Y) <= this.cornerWidth)
{ // 右下
return new IntPtr((int)HitTest.HTBOTTOMRIGHT);
}
else if (Math.Abs(this.ActualWidth + this.Left - this.mousePoint.X) <= 4 && Math.Abs(this.mousePoint.Y - this.Top) > 50)
{ // 右
return new IntPtr((int)HitTest.HTRIGHT);
}
else if (Math.Abs(this.ActualHeight + this.Top - this.mousePoint.Y) <= 4)
{ // 底部
return new IntPtr((int)HitTest.HTBOTTOM);
}
}
handled = false;
return IntPtr.Zero;
}
19
Source : DellSmbiosSmi.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from AaronKelley
private static uint? GetSecurityKeyNew(SmiPreplacedword which, string preplacedword, PreplacedwordProperties properties)
{
// NOTE – Non-functional, need to figure out the string pointer before it will work.
if (GetPreplacedwordFormat(which, properties) == SmiPreplacedwordFormat.Scancode)
{
throw new NotImplementedException("BIOS wants scancode-encoded preplacedwords, but only ASCII-encoded preplacedwords are supported at this time.");
}
SmiObject message = new SmiObject
{
Clreplaced = (Clreplaced)which,
Selector = Selector.VerifyPreplacedwordNew
};
// Allocate a buffer for the preplacedword.
int bufferSize = properties.MaximumLength * 2;
IntPtr buffer = Marshal.AllocHGlobal(bufferSize);
// Zero out the buffer.
for (byte index = 0; index < bufferSize; index++)
{
Marshal.WriteByte(buffer, index, 0);
}
// Copy preplacedword into the buffer (ASCII-encoded).
byte[] preplacedwordBytes = ASCIIEncoding.ASCII.GetBytes(preplacedword);
Marshal.Copy(preplacedwordBytes, 0, buffer, Math.Min(preplacedword.Length, bufferSize));
message.Input1 = (uint)buffer.ToInt32();
ExecuteCommand(ref message);
Marshal.FreeHGlobal(buffer);
if (message.Input1 == (uint)SmiPreplacedwordCheckResult.Correct)
{
return message.Input2;
}
else
{
return null;
}
}
19
Source : SimpleEditor.cs
with GNU General Public License v3.0
from adam8797
with GNU General Public License v3.0
from adam8797
private int GetIndent(int line)
{
return (DirectMessage(SCI_GETLINEINDENTATION, new IntPtr(line), IntPtr.Zero).ToInt32());
}
19
Source : WindowInBandWrapper.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
private IntPtr myWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
switch (msg)
{
case WM_PAINT:
break;
case WM_LBUTTONDBLCLK:
break;
case WM_DESTROY:
DestroyWindow(hWnd);
break;
case WM_DPICHANGED:
_DPI = (wParam.ToInt32() & 0xFFFF) / 96D;
UpdateSize();
break;
default:
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
19
Source : NativeMethods.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public static IntPtr SetClreplacedLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
{
if (IntPtr.Size > 4)
return SetClreplacedLongPtr64(hWnd, nIndex, dwNewLong);
else
return new IntPtr(SetClreplacedLongPtr32(hWnd, nIndex, unchecked((uint)dwNewLong.ToInt32())));
}
19
Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from adrianlungu
with GNU General Public License v3.0
from adrianlungu
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == 0x0312 && wParam.ToInt32() == Settings.HotkeyId)
{
Task.Delay(1000 * Properties.Settings.Default.SleepTimer).ContinueWith(t => TurnOff_OnClick(null, null));
}
return IntPtr.Zero;
}
19
Source : InteropMethods.cs
with GNU General Public License v3.0
from aduskin
with GNU General Public License v3.0
from aduskin
internal static IntPtr SetWindowLongPtr(IntPtr hWnd, InteropValues.GWLP nIndex, IntPtr dwNewLong)
{
if (IntPtr.Size == 8)
{
return SetWindowLongPtr(hWnd, (int)nIndex, dwNewLong);
}
return new IntPtr(SetWindowLong(hWnd, (int)nIndex, dwNewLong.ToInt32()));
}
19
Source : Unicorn.cs
with MIT License
from AeonLucid
with MIT License
from AeonLucid
private void HookMemCallback(IntPtr uc, UcMemType type, ulong address, int size, long value, IntPtr userData)
{
var callbackData = _callbacks[userData.ToInt32()];
((CallbackHookMemUser) callbackData.UserCallback)(this, type, address, size, value, callbackData.UserData);
}
19
Source : Unicorn.cs
with MIT License
from AeonLucid
with MIT License
from AeonLucid
private bool HookMemEventCallback(IntPtr uc, UcMemType type, ulong address, int size, long value, IntPtr userData)
{
var callbackData = _callbacks[userData.ToInt32()];
return ((CallbackEventMemUser) callbackData.UserCallback)(this, type, address, size, value, callbackData.UserData);
}
19
Source : CRTInjection.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public override IntPtr Inject(string dllPath, IntPtr hProcess)
{
this.ClearErrors();
if (hProcess.IsNull() || hProcess.Compare(-1L))
{
throw new ArgumentOutOfRangeException("hProcess", "Invalid process handle specified.");
}
try
{
IntPtr zero = IntPtr.Zero;
IntPtr procAddress = WinAPI.GetProcAddress(WinAPI.GetModuleHandleA("kernel32.dll"), "LoadLibraryW");
if (procAddress.IsNull())
{
throw new Exception("Unable to locate the LoadLibraryW entry point");
}
IntPtr ptr = WinAPI.CreateRemotePointer(hProcess, Encoding.Unicode.GetBytes(dllPath + "\0"), 4);
if (ptr.IsNull())
{
throw new InvalidOperationException("Failed to allocate memory in the remote process");
}
try
{
uint num = WinAPI.RunThread(hProcess, procAddress, (uint) ptr.ToInt32(), 0x2710);
switch (num)
{
case uint.MaxValue:
throw new Exception("Error occurred when calling function in the remote process");
case 0:
throw new Exception("Failed to load module into remote process. Error code: " + WinAPI.GetLastErrorEx(hProcess).ToString());
}
zero = Win32Ptr.Create((long) num);
}
finally
{
WinAPI.VirtualFreeEx(hProcess, ptr, 0, 0x8000);
}
return zero;
}
catch (Exception exception)
{
this.SetLastError(exception);
return IntPtr.Zero;
}
}
19
Source : ManualMap.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
private static bool LoadDependencies(JLibrary.PortableExecutable.PortableExecutable image, IntPtr hProcess, int processId)
{
List<string> list = new List<string>();
string lpBuffer = string.Empty;
bool flag = false;
foreach (IMAGE_IMPORT_DESCRIPTOR image_import_descriptor in image.EnumImports())
{
if ((image.ReadString((long) image.GetPtrFromRVA(image_import_descriptor.Name), SeekOrigin.Begin, out lpBuffer, -1, null) && !string.IsNullOrEmpty(lpBuffer)) && GetRemoteModuleHandle(lpBuffer, processId).IsNull())
{
list.Add(lpBuffer);
}
}
if (list.Count > 0)
{
byte[] data = ExtractManifest(image);
string str2 = string.Empty;
if (data == null)
{
if (string.IsNullOrEmpty(image.FileLocation) || !File.Exists(Path.Combine(Path.GetDirectoryName(image.FileLocation), Path.GetFileName(image.FileLocation) + ".manifest")))
{
IntPtr[] ptrArray = InjectionMethod.Create(InjectionMethodType.Standard).InjectAll(list.ToArray(), hProcess);
foreach (IntPtr ptr in ptrArray)
{
if (ptr.IsNull())
{
return false;
}
}
return true;
}
str2 = Path.Combine(Path.GetDirectoryName(image.FileLocation), Path.GetFileName(image.FileLocation) + ".manifest");
}
else
{
str2 = Utils.WriteTempData(data);
}
if (string.IsNullOrEmpty(str2))
{
return false;
}
IntPtr ptr2 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) RESOLVER_STUB.Length, 0x3000, 0x40);
IntPtr lpAddress = WinAPI.CreateRemotePointer(hProcess, Encoding.ASCII.GetBytes(str2 + "\0"), 4);
IntPtr ptr4 = WinAPI.CreateRemotePointer(hProcess, Encoding.ASCII.GetBytes(string.Join("\0", list.ToArray()) + "\0"), 4);
if (!ptr2.IsNull())
{
byte[] array = (byte[]) RESOLVER_STUB.Clone();
uint lpNumberOfBytesRead = 0;
BitConverter.GetBytes(FN_CREATEACTCTXA.Subtract(ptr2.Add(((long) 0x3fL))).ToInt32()).CopyTo(array, 0x3b);
BitConverter.GetBytes(FN_ACTIVATEACTCTX.Subtract(ptr2.Add(((long) 0x58L))).ToInt32()).CopyTo(array, 0x54);
BitConverter.GetBytes(FN_GETMODULEHANDLEA.Subtract(ptr2.Add(((long) 0x84L))).ToInt32()).CopyTo(array, 0x80);
BitConverter.GetBytes(FN_LOADLIBRARYA.Subtract(ptr2.Add(((long) 0x92L))).ToInt32()).CopyTo(array, 0x8e);
BitConverter.GetBytes(FN_DEACTIVATEACTCTX.Subtract(ptr2.Add(((long) 200L))).ToInt32()).CopyTo(array, 0xc4);
BitConverter.GetBytes(FN_RELEASEACTCTX.Subtract(ptr2.Add(((long) 0xd1L))).ToInt32()).CopyTo(array, 0xcd);
BitConverter.GetBytes(lpAddress.ToInt32()).CopyTo(array, 0x1f);
BitConverter.GetBytes(list.Count).CopyTo(array, 40);
BitConverter.GetBytes(ptr4.ToInt32()).CopyTo(array, 0x31);
if (WinAPI.WriteProcessMemory(hProcess, ptr2, array, array.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == array.Length))
{
uint num2 = WinAPI.RunThread(hProcess, ptr2, 0, 0x1388);
flag = (num2 != uint.MaxValue) && (num2 != 0);
}
WinAPI.VirtualFreeEx(hProcess, ptr4, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, lpAddress, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, ptr2, 0, 0x8000);
}
}
return flag;
}
19
Source : ManualMap.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
private static IntPtr MapModule(JLibrary.PortableExecutable.PortableExecutable image, IntPtr hProcess, bool preserveHeaders = false)
{
if (hProcess.IsNull() || hProcess.Compare(-1L))
{
throw new ArgumentException("Invalid process handle.", "hProcess");
}
if (image == null)
{
throw new ArgumentException("Cannot map a non-existant PE Image.", "image");
}
int processId = WinAPI.GetProcessId(hProcess);
if (processId == 0)
{
throw new ArgumentException("Provided handle doesn't have sufficient permissions to inject", "hProcess");
}
IntPtr zero = IntPtr.Zero;
IntPtr ptr = IntPtr.Zero;
uint lpNumberOfBytesRead = 0;
try
{
zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, image.NTHeader.OptionalHeader.SizeOfImage, 0x3000, 4);
if (zero.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process.");
}
PatchRelocations(image, zero);
LoadDependencies(image, hProcess, processId);
PatchImports(image, hProcess, processId);
if (preserveHeaders)
{
long num3 = (long) (((image.DOSHeader.e_lfanew + Marshal.SizeOf(typeof(IMAGE_FILE_HEADER))) + ((long) 4L)) + image.NTHeader.FileHeader.SizeOfOptionalHeader);
byte[] buffer = new byte[num3];
if (image.Read(0L, SeekOrigin.Begin, buffer))
{
WinAPI.WriteProcessMemory(hProcess, zero, buffer, buffer.Length, out lpNumberOfBytesRead);
}
}
MapSections(image, hProcess, zero);
if (image.NTHeader.OptionalHeader.AddressOfEntryPoint <= 0)
{
return zero;
}
byte[] array = (byte[]) DLLMAIN_STUB.Clone();
BitConverter.GetBytes(zero.ToInt32()).CopyTo(array, 11);
ptr = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) DLLMAIN_STUB.Length, 0x3000, 0x40);
if (ptr.IsNull() || (!WinAPI.WriteProcessMemory(hProcess, ptr, array, array.Length, out lpNumberOfBytesRead) || (lpNumberOfBytesRead != array.Length)))
{
throw new InvalidOperationException("Unable to write stub to the remote process.");
}
IntPtr hObject = WinAPI.CreateRemoteThread(hProcess, 0, 0, ptr, (uint) zero.Add(((long) image.NTHeader.OptionalHeader.AddressOfEntryPoint)).ToInt32(), 0, 0);
if (WinAPI.WaitForSingleObject(hObject, 0x1388) != 0L)
{
return zero;
}
WinAPI.GetExitCodeThread(hObject, out lpNumberOfBytesRead);
if (lpNumberOfBytesRead == 0)
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
throw new Exception("Entry method of module reported a failure " + Marshal.GetLastWin32Error().ToString());
}
WinAPI.VirtualFreeEx(hProcess, ptr, 0, 0x8000);
WinAPI.CloseHandle(hObject);
}
catch (Exception exception)
{
if (!zero.IsNull())
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
}
if (!ptr.IsNull())
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
}
zero = IntPtr.Zero;
throw exception;
}
return zero;
}
19
Source : ManualMap.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
private static void PatchImports(JLibrary.PortableExecutable.PortableExecutable image, IntPtr hProcess, int processId)
{
string lpBuffer = string.Empty;
string str2 = string.Empty;
foreach (IMAGE_IMPORT_DESCRIPTOR image_import_descriptor in image.EnumImports())
{
if (image.ReadString((long) image.GetPtrFromRVA(image_import_descriptor.Name), SeekOrigin.Begin, out lpBuffer, -1, null))
{
IMAGE_THUNK_DATA image_thunk_data;
IntPtr zero = IntPtr.Zero;
zero = GetRemoteModuleHandle(lpBuffer, processId);
if (zero.IsNull())
{
throw new FileNotFoundException(string.Format("Unable to load dependent module '{0}'.", lpBuffer));
}
uint ptrFromRVA = image.GetPtrFromRVA(image_import_descriptor.FirstThunkPtr);
uint num2 = (uint) Marshal.SizeOf(typeof(IMAGE_THUNK_DATA));
while (image.Read<IMAGE_THUNK_DATA>((long) ptrFromRVA, SeekOrigin.Begin, out image_thunk_data) && (image_thunk_data.u1.AddressOfData > 0))
{
IntPtr hModule = IntPtr.Zero;
object lpProcName = null;
if ((image_thunk_data.u1.Ordinal & 0x80000000) == 0)
{
if (!image.ReadString((long) (image.GetPtrFromRVA(image_thunk_data.u1.AddressOfData) + 2), SeekOrigin.Begin, out str2, -1, null))
{
throw image.GetLastError();
}
lpProcName = str2;
}
else
{
lpProcName = (ushort) (image_thunk_data.u1.Ordinal & 0xffff);
}
if (!(hModule = WinAPI.GetModuleHandleA(lpBuffer)).IsNull())
{
IntPtr ptr = lpProcName.GetType().Equals(typeof(string)) ? WinAPI.GetProcAddress(hModule, (string) lpProcName) : WinAPI.GetProcAddress(hModule, (uint) (((ushort) lpProcName) & 0xffff));
if (!ptr.IsNull())
{
hModule = zero.Add((long) ptr.Subtract(((long) hModule.ToInt32())).ToInt32());
}
}
else
{
hModule = WinAPI.GetProcAddressEx(hProcess, zero, lpProcName);
}
if (hModule.IsNull())
{
throw new EntryPointNotFoundException(string.Format("Unable to locate imported function '{0}' from module '{1}' in the remote process.", str2, lpBuffer));
}
image.Write<int>((long) ptrFromRVA, SeekOrigin.Begin, hModule.ToInt32());
ptrFromRVA += num2;
}
}
}
}
19
Source : StandardInjectionMethod.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
protected virtual IntPtr CreateMultiLoadStub(string[] paths, IntPtr hProcess, out IntPtr pModuleBuffer, uint nullmodule = 0)
{
IntPtr ptr6;
pModuleBuffer = IntPtr.Zero;
IntPtr zero = IntPtr.Zero;
try
{
IntPtr moduleHandleA = WinAPI.GetModuleHandleA("kernel32.dll");
IntPtr procAddress = WinAPI.GetProcAddress(moduleHandleA, "LoadLibraryA");
IntPtr ptr = WinAPI.GetProcAddress(moduleHandleA, "GetModuleHandleA");
if (procAddress.IsNull() || ptr.IsNull())
{
throw new Exception("Unable to find necessary function entry points in the remote process");
}
pModuleBuffer = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, ((uint) paths.Length) << 2, 0x3000, 4);
IntPtr ptr5 = WinAPI.CreateRemotePointer(hProcess, Encoding.ASCII.GetBytes(string.Join("\0", paths) + "\0"), 4);
if (pModuleBuffer.IsNull() || ptr5.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process");
}
try
{
uint lpNumberOfBytesRead = 0;
byte[] array = new byte[paths.Length << 2];
for (int i = 0; i < (array.Length >> 2); i++)
{
BitConverter.GetBytes(nullmodule).CopyTo(array, (int) (i << 2));
}
WinAPI.WriteProcessMemory(hProcess, pModuleBuffer, array, array.Length, out lpNumberOfBytesRead);
byte[] buffer2 = (byte[]) MULTILOAD_STUB.Clone();
zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) buffer2.Length, 0x3000, 0x40);
if (zero.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process");
}
BitConverter.GetBytes(ptr5.ToInt32()).CopyTo(buffer2, 7);
BitConverter.GetBytes(paths.Length).CopyTo(buffer2, 15);
BitConverter.GetBytes(pModuleBuffer.ToInt32()).CopyTo(buffer2, 0x18);
BitConverter.GetBytes(ptr.Subtract(zero.Add(((long) 0x38L))).ToInt32()).CopyTo(buffer2, 0x34);
BitConverter.GetBytes(procAddress.Subtract(zero.Add(((long) 0x45L))).ToInt32()).CopyTo(buffer2, 0x41);
if (!(WinAPI.WriteProcessMemory(hProcess, zero, buffer2, buffer2.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == buffer2.Length)))
{
throw new Exception("Error creating the remote function stub.");
}
ptr6 = zero;
}
finally
{
WinAPI.VirtualFreeEx(hProcess, pModuleBuffer, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, ptr5, 0, 0x8000);
if (!zero.IsNull())
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
}
pModuleBuffer = IntPtr.Zero;
}
}
catch (Exception exception)
{
this.SetLastError(exception);
ptr6 = IntPtr.Zero;
}
return ptr6;
}
19
Source : StandardInjectionMethod.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public override bool[] UnloadAll(IntPtr[] hModules, IntPtr hProcess)
{
bool[] flagArray2;
this.ClearErrors();
IntPtr zero = IntPtr.Zero;
IntPtr ptr = IntPtr.Zero;
IntPtr ptr3 = IntPtr.Zero;
try
{
int num2;
uint lpNumberOfBytesRead = 0;
IntPtr procAddress = WinAPI.GetProcAddress(WinAPI.GetModuleHandleA("kernel32.dll"), "FreeLibrary");
if (procAddress.IsNull())
{
throw new Exception("Unable to find necessary function entry points in the remote process");
}
zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, ((uint) hModules.Length) << 2, 0x3000, 4);
ptr = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) ((hModules.Length + 1) << 2), 0x3000, 4);
ptr3 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) MULTIUNLOAD_STUB.Length, 0x3000, 0x40);
if ((zero.IsNull() || ptr.IsNull()) || ptr3.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process");
}
byte[] array = new byte[(hModules.Length + 1) << 2];
for (num2 = 0; num2 < hModules.Length; num2++)
{
BitConverter.GetBytes(hModules[num2].ToInt32()).CopyTo(array, (int) (num2 << 2));
}
WinAPI.WriteProcessMemory(hProcess, ptr, array, array.Length, out lpNumberOfBytesRead);
byte[] buffer2 = (byte[]) MULTIUNLOAD_STUB.Clone();
BitConverter.GetBytes(ptr.ToInt32()).CopyTo(buffer2, 7);
BitConverter.GetBytes(zero.ToInt32()).CopyTo(buffer2, 15);
BitConverter.GetBytes(procAddress.Subtract(ptr3.Add(((long) 0x38L))).ToInt32()).CopyTo(buffer2, 0x34);
if (!(WinAPI.WriteProcessMemory(hProcess, ptr3, buffer2, buffer2.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == buffer2.Length)))
{
throw new InvalidOperationException("Unable to write the function stub to the remote process.");
}
if (WinAPI.RunThread(hProcess, ptr3, 0, 0x3e8) == uint.MaxValue)
{
throw new InvalidOperationException("Error occurred when running remote function stub.");
}
byte[] buffer3 = WinAPI.ReadRemoteMemory(hProcess, zero, ((uint) hModules.Length) << 2);
if (buffer3 == null)
{
throw new Exception("Unable to read results from the remote process.");
}
bool[] flagArray = new bool[hModules.Length];
for (num2 = 0; num2 < flagArray.Length; num2++)
{
flagArray[num2] = BitConverter.ToInt32(buffer3, num2 << 2) != 0;
}
flagArray2 = flagArray;
}
catch (Exception exception)
{
this.SetLastError(exception);
flagArray2 = null;
}
finally
{
WinAPI.VirtualFreeEx(hProcess, ptr3, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, ptr, 0, 0x8000);
}
return flagArray2;
}
19
Source : ThreadHijack.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public override IntPtr[] InjectAll(string[] dllPaths, IntPtr hProcess)
{
Exception exception;
this.ClearErrors();
try
{
if (hProcess.IsNull() || hProcess.Compare(-1L))
{
throw new ArgumentException("Invalid process handle.", "hProcess");
}
int processId = WinAPI.GetProcessId(hProcess);
if (processId == 0)
{
throw new ArgumentException("Provided handle doesn't have sufficient permissions to inject", "hProcess");
}
Process processById = Process.GetProcessById(processId);
if (processById.Threads.Count == 0)
{
throw new Exception("Target process has no targetable threads to hijack.");
}
ProcessThread thread = SelectOptimalThread(processById);
IntPtr ptr = WinAPI.OpenThread(0x1a, false, thread.Id);
if (ptr.IsNull() || ptr.Compare(-1L))
{
throw new Exception("Unable to obtain a handle for the remote thread.");
}
IntPtr zero = IntPtr.Zero;
IntPtr lpAddress = IntPtr.Zero;
IntPtr ptr4 = this.CreateMultiLoadStub(dllPaths, hProcess, out zero, 1);
IntPtr[] ptrArray = null;
if (!ptr4.IsNull())
{
if (WinAPI.SuspendThread(ptr) == uint.MaxValue)
{
throw new Exception("Unable to suspend the remote thread");
}
try
{
uint lpNumberOfBytesRead = 0;
WinAPI.CONTEXT pContext = new WinAPI.CONTEXT {
ContextFlags = 0x10001
};
if (!WinAPI.GetThreadContext(ptr, ref pContext))
{
throw new InvalidOperationException("Cannot get the remote thread's context");
}
byte[] array = REDIRECT_STUB;
IntPtr ptr5 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) array.Length, 0x3000, 0x40);
if (ptr5.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process.");
}
BitConverter.GetBytes(ptr4.Subtract(ptr5.Add(((long) 7L))).ToInt32()).CopyTo(array, 3);
BitConverter.GetBytes((uint) (pContext.Eip - ((uint) ptr5.Add(((long) array.Length)).ToInt32()))).CopyTo(array, (int) (array.Length - 4));
if (!(WinAPI.WriteProcessMemory(hProcess, ptr5, array, array.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == array.Length)))
{
throw new InvalidOperationException("Unable to write stub to the remote process.");
}
pContext.Eip = (uint) ptr5.ToInt32();
WinAPI.SetThreadContext(ptr, ref pContext);
}
catch (Exception exception1)
{
exception = exception1;
this.SetLastError(exception);
ptrArray = null;
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, ptr4, 0, 0x8000);
WinAPI.VirtualFreeEx(hProcess, lpAddress, 0, 0x8000);
}
WinAPI.ResumeThread(ptr);
if (this.GetLastError() == null)
{
Thread.Sleep(100);
ptrArray = new IntPtr[dllPaths.Length];
byte[] buffer2 = WinAPI.ReadRemoteMemory(hProcess, zero, ((uint) dllPaths.Length) << 2);
if (buffer2 != null)
{
for (int i = 0; i < ptrArray.Length; i++)
{
ptrArray[i] = Win32Ptr.Create((long) BitConverter.ToInt32(buffer2, i << 2));
}
}
}
WinAPI.CloseHandle(ptr);
}
return ptrArray;
}
catch (Exception exception2)
{
exception = exception2;
this.SetLastError(exception);
return null;
}
}
19
Source : Unicorn.cs
with MIT License
from AeonLucid
with MIT License
from AeonLucid
private void HookCodeCallback(IntPtr uc, ulong address, int size, IntPtr userData)
{
var callbackData = _callbacks[userData.ToInt32()];
((CallbackHookCodeUser) callbackData.UserCallback)(this, address, size, callbackData.UserData);
}
19
Source : Unicorn.cs
with MIT License
from AeonLucid
with MIT License
from AeonLucid
private bool HookInsnInvalidCallback(IntPtr uc, IntPtr userData)
{
var callbackData = _callbacks[userData.ToInt32()];
return ((CallbackHookInsnInvalidUser) callbackData.UserCallback)(this, callbackData.UserData);
}
19
Source : ManualMap.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
private static void PatchRelocations(JLibrary.PortableExecutable.PortableExecutable image, IntPtr pAlloc)
{
IMAGE_DATA_DIRECTORY image_data_directory = image.NTHeader.OptionalHeader.DataDirectory[5];
if (image_data_directory.Size > 0)
{
IMAGE_BASE_RELOCATION image_base_relocation;
uint num = 0;
uint num2 = ((uint) pAlloc.ToInt32()) - image.NTHeader.OptionalHeader.ImageBase;
uint ptrFromRVA = image.GetPtrFromRVA(image_data_directory.VirtualAddress);
uint num4 = (uint) Marshal.SizeOf(typeof(IMAGE_BASE_RELOCATION));
while ((num < image_data_directory.Size) && image.Read<IMAGE_BASE_RELOCATION>((long) ptrFromRVA, SeekOrigin.Begin, out image_base_relocation))
{
int num5 = (int) ((image_base_relocation.SizeOfBlock - num4) / 2);
uint num6 = image.GetPtrFromRVA(image_base_relocation.VirtualAddress);
for (int i = 0; i < num5; i++)
{
ushort num7;
if (image.Read<ushort>((ptrFromRVA + num4) + (i << 1), SeekOrigin.Begin, out num7) && (((num7 >> 12) & 3) != 0))
{
uint num8;
uint num10 = num6 + ((uint) (num7 & 0xfff));
if (!image.Read<uint>((long) num10, SeekOrigin.Begin, out num8))
{
throw image.GetLastError();
}
image.Write<uint>(-4L, SeekOrigin.Current, num8 + num2);
}
}
num += image_base_relocation.SizeOfBlock;
ptrFromRVA += image_base_relocation.SizeOfBlock;
}
}
}
19
Source : Win32Ptr.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public static IntPtr Add(this IntPtr ptr, IntPtr val)
{
return new IntPtr(ptr.ToInt32() + val.ToInt32());
}
19
Source : WinAPI.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public static IntPtr GetModuleHandleEx(IntPtr hProcess, string lpModuleName)
{
IntPtr procAddress = GetProcAddress(GetModuleHandleA("kernel32.dll"), "GetModuleHandleW");
IntPtr zero = IntPtr.Zero;
if (!procAddress.IsNull())
{
IntPtr ptr = CreateRemotePointer(hProcess, Encoding.Unicode.GetBytes(lpModuleName + "\0"), 4);
if (!ptr.IsNull())
{
zero = Win32Ptr.Create((long) RunThread(hProcess, procAddress, (uint) ptr.ToInt32(), 0x3e8));
VirtualFreeEx(hProcess, ptr, 0, 0x8000);
}
}
return zero;
}
19
Source : Unicorn.cs
with MIT License
from AeonLucid
with MIT License
from AeonLucid
private void HookIntrCallback(IntPtr uc, uint intno, IntPtr userData)
{
var callbackData = _callbacks[userData.ToInt32()];
((CallbackHookIntrUser) callbackData.UserCallback)(this, intno, callbackData.UserData);
}
19
Source : ManualMap.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public override bool Unload(IntPtr hModule, IntPtr hProcess)
{
this.ClearErrors();
if (hModule.IsNull())
{
throw new ArgumentNullException("hModule", "Invalid module handle");
}
if (hProcess.IsNull() || hProcess.Compare(-1L))
{
throw new ArgumentException("Invalid process handle.", "hProcess");
}
IntPtr zero = IntPtr.Zero;
uint lpNumberOfBytesRead = 0;
try
{
uint num2 = FindEntryPoint(hProcess, hModule);
if (num2 != 0)
{
byte[] array = (byte[]) DLLMAIN_STUB.Clone();
BitConverter.GetBytes(hModule.ToInt32()).CopyTo(array, 11);
BitConverter.GetBytes((uint) 0).CopyTo(array, 6);
BitConverter.GetBytes((uint) 0x3e8).CopyTo(array, 1);
zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) DLLMAIN_STUB.Length, 0x3000, 0x40);
if (zero.IsNull() || (!WinAPI.WriteProcessMemory(hProcess, zero, array, array.Length, out lpNumberOfBytesRead) || (lpNumberOfBytesRead != array.Length)))
{
throw new InvalidOperationException("Unable to write stub to the remote process.");
}
IntPtr hObject = WinAPI.CreateRemoteThread(hProcess, 0, 0, zero, (uint) hModule.Add(((long) num2)).ToInt32(), 0, 0);
if (WinAPI.WaitForSingleObject(hObject, 0x1388) == 0L)
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
WinAPI.CloseHandle(hObject);
return WinAPI.VirtualFreeEx(hProcess, hModule, 0, 0x8000);
}
return false;
}
return WinAPI.VirtualFreeEx(hProcess, hModule, 0, 0x8000);
}
catch (Exception exception)
{
this.SetLastError(exception);
return false;
}
}
19
Source : Win32Ptr.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public static IntPtr Add(this IntPtr ptr, long val)
{
return new IntPtr(ptr.ToInt32() + ((int) val));
}
19
Source : TextCaptureEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string GetIExploreUrl(IntPtr hWnd)
{
string url = null;
try
{
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClreplaced();
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
if (ie.HWND == hWnd.ToInt32())
{
url = ie.LocationURL;
break;
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
return url;
}
19
Source : TextCaptureEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string GetChromeUrl(IntPtr hWnd)
{
string url = null;
try
{
IntPtr hAddressWnd = User32.FindWindowEx(hWnd, IntPtr.Zero, "Chrome_OmniboxView", "");
if (hAddressWnd != IntPtr.Zero)
{
StringBuilder sb = new StringBuilder(2083);
User32.SendMessage(hAddressWnd, User32.WM_GETTEXT, 2083, sb);
url = sb.ToString();
}
else
{
var wnd = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NativeWindowHandleProperty, hWnd.ToInt32()));
if (wnd != null)
{
var edit = wnd.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
if (edit != null)
{
var val = edit.GetCurrentPropertyValue(ValuePattern.ValueProperty, false);
if (val != null)
url = val.ToString();
}
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
return url;
}
19
Source : TextCaptureEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string GetMaxthonUrl(IntPtr hWnd)
{
string url = null;
try
{
var wnd = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NativeWindowHandleProperty, hWnd.ToInt32()));
if (wnd != null)
{
var edit = wnd.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
if (edit != null)
{
var val = edit.GetCurrentPropertyValue(ValuePattern.ValueProperty, false);
if (val != null)
url = val.ToString();
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
return url;
}
19
Source : TextCaptureEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string GetSogouUrl(IntPtr hWnd)
{
string url = null;
try
{
var wnd = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NativeWindowHandleProperty, hWnd.ToInt32()));
if (wnd != null)
{
var pane = wnd.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ClreplacedNameProperty, "SE_TuotuoAddressBarEditCtrl"));
if (pane != null)
{
var val = pane.GetCurrentPropertyValue(AutomationElement.NameProperty);
if (val != null)
url = val.ToString();
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
return url;
}
19
Source : TextCaptureEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string GetMiniIEUrl(IntPtr hWnd)
{
string url = null;
try
{
var wnd = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NativeWindowHandleProperty, hWnd.ToInt32()));
if (wnd != null)
{
var pane = wnd.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.ClreplacedNameProperty, "ThunderRT6ComboBox"));
if (pane != null)
{
var val = pane.GetCurrentPropertyValue(AutomationElement.NameProperty);
if (val != null)
url = val.ToString();
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
return url;
}
19
Source : SnapshotEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static WindowInfo GetActiveProcessWindow()
{
WindowInfo wi = new WindowInfo();
try
{
IntPtr hWnd = GetForegroundWindow();
if (hWnd != IntPtr.Zero)
{
Process process = GetWindowProcess(hWnd);
if (process != null)
{
try
{
wi.ProcessId = process.Id;
wi.ProcessName = process.ProcessName;
wi.FileName = GetProcessFile(process.Id);
}
catch (Exception ex) { TraceLogger.Instance.WriteLineInfo("Open process fail:" + wi.ProcessName); TraceLogger.Instance.WriteException(ex); }
process.Dispose();
}
wi.ScreenWidth = Screen.PrimaryScreen.Bounds.Width;
wi.ScreenHeight = Screen.PrimaryScreen.Bounds.Height;
wi.WindowHandle = hWnd.ToInt32();
wi.WindowRect = WindowCaptureEngine.GetWindowRect(hWnd);
wi.Windowreplacedle = TextCaptureEngine.GetWindowreplacedle(hWnd);
wi.WindowUrl = TextCaptureEngine.GetWindowUrl(hWnd);
///? GetControlText cause double click invalid.
//wi.ControlText = TextCaptureEngine.GetControlText(hWnd);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return wi;
}
19
Source : AccessPolicy.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private IEnumerable<MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCPROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
Source : AccessPolicy.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private IEnumerable<MIB_TCP6ROW_OWNER_PID> EnumTcpConnectionsV6()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCP6ROW_OWNER_PID item = new MIB_TCP6ROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCP6ROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
Source : TcpEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static IEnumerable<MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCPROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
Source : TcpEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static IEnumerable<MIB_TCP6ROW_OWNER_PID> EnumTcpConnectionsV6()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCP6ROW_OWNER_PID item = new MIB_TCP6ROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCP6ROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
Source : WinApiService.cs
with Apache License 2.0
from AKruimink
with Apache License 2.0
from AKruimink
public IntPtr SetWindowLongPtr(IntPtr hwnd, GwlType nIndex, IntPtr dwNewLong)
{
IntPtr returnValue;
if (IntPtr.Size == 8)
{
// 64 bit system
returnValue = SetWindowLongPtr64(hwnd, nIndex, dwNewLong);
}
else
{
// 32 bit system
returnValue = (IntPtr)SetWindowLongPtr32(hwnd, nIndex, dwNewLong.ToInt32());
}
if (returnValue == IntPtr.Zero)
{
HResult.ThrowLastError();
}
return returnValue;
}
19
Source : AudioKernelExtensions.cs
with MIT License
from aksyr
with MIT License
from aksyr
public static void Execute(ref TAudioKernel kernel, IntPtr audioDataPtr, IntPtr functionIndex, ref JobRanges ranges, int ignored2)
{
switch (functionIndex.ToInt32())
{
case 0:
ExecuteKernel(ref kernel, audioDataPtr);
break;
case 1:
InitializeKernel(ref kernel);
break;
case 2:
DisposeKernel(ref kernel);
break;
case 3:
ExecuteKernelWithWrapper(audioDataPtr);
break;
default:
throw new ArgumentException($"Invalid function index {functionIndex}", nameof(functionIndex));
}
}
19
Source : AudioOutputExtensions.cs
with MIT License
from aksyr
with MIT License
from aksyr
public static unsafe void Execute(ref TOutput data, IntPtr userData, IntPtr method, ref JobRanges ranges, int jobIndex)
{
var methodID = (MethodID)method.ToInt32();
switch (methodID)
{
case MethodID.BeginMix:
{
var champleCount = userData.ToInt32();
data.BeginMix(champleCount);
break;
}
case MethodID.EndMix:
{
UnsafeUtility.CopyPtrToStructure(userData.ToPointer(), out EndMixData endMixData);
var length = endMixData.ChannelCount * endMixData.ChampleCount;
var nativeBuffer = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float>(endMixData.Buffer, length, Allocator.Invalid);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nativeBuffer, endMixData.Safety);
#endif
var frameCount = endMixData.ChampleCount / endMixData.ChannelCount;
data.EndMix(nativeBuffer, frameCount);
break;
}
case MethodID.Dispose:
{
data.Dispose();
break;
}
case MethodID.Initialize:
{
var initializationData = (InitializationData*)userData;
data.Initialize(initializationData->ChannelCount, initializationData->SoundFormat, initializationData->SampleRate, initializationData->DSPBufferSize);
break;
}
default:
throw new ArgumentOutOfRangeException();
}
}
19
Source : KeyboardHook.cs
with MIT License
from AlexanderPro
with MIT License
from AlexanderPro
private int HookProc(int code, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam)
{
if (code == NativeConstants.HC_ACTION)
{
if (wParam.ToInt32() == NativeConstants.WM_KEYDOWN || wParam.ToInt32() == NativeConstants.WM_SYSKEYDOWN)
{
var key1 = true;
var key2 = true;
if (_key1 != (int)VirtualKeyModifier.None)
{
var key1State = NativeMethods.GetAsyncKeyState(_key1) & 0x8000;
key1 = Convert.ToBoolean(key1State);
}
if (_key2 != (int)VirtualKeyModifier.None)
{
var key2State = NativeMethods.GetAsyncKeyState(_key2) & 0x8000;
key2 = Convert.ToBoolean(key2State);
}
if (key1 && key2 && lParam.vkCode == _key3)
{
var handler = Hooked;
if (handler != null)
{
handler.BeginInvoke(this, EventArgs.Empty, null, null);
}
}
}
}
return NativeMethods.CallNextHookEx(_hookHandle, code, wParam, ref lParam);
}
See More Examples