Issues with injection code - c#

So after looking around online, and debugging the code I found out that there are issues with using CreateRemoteThread and CreateRemoteThreadEx on windows 8, 8.1, and 10 (The dll does not inject at all). The code works fine for anyone who is not using windows 8+. I was wondering if anyone could help me debug the code in order for it to work on the newer operating system, and if possible to provide a explanation to why it is not working. This is the first time I looked into c#, I mainly program in Java.
While I was following the stack I know that it is coming from InjectLibrary in Injector.cs
// load dll via call to LoadLibrary using CreateRemoteThread
hThread = Imports.CreateRemoteThread(_handle, IntPtr.Zero, 0, hLoadLib, pLibRemote, 0, IntPtr.Zero);
Program.cs:
using System;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Syringe;
namespace GameLauncherEx
{
class Program
{
// Injector code by adaephon on ownedcore
// www.ownedcore.com/forums/world-of-warcraft/world-of-warcraft-bots-programs/wow-memory-editing/265219-c-net-dll-injector.html
static void Main(string[] args)
{
string ip = "127.0.0.1";
int maxTryCount = 5;
int waitWindowSleep = 1;
int failInjectSleep = 500;
string dll = "IPRedirect.dll";
string client = string.Format("{0}\\MapleStory.exe", Environment.CurrentDirectory);
if (!File.Exists(client))
{
MessageBox.Show("Couldn't find MapleStory.exe", "GameLauncherEx");
return;
}
if (!File.Exists(string.Format("{0}\\{1}", Environment.CurrentDirectory, dll)))
{
MessageBox.Show("Couldn't find IPRedirect.dll", "GameLauncherEx");
return;
}
IPAddress ipAddress;
if (args.Length >= 1 && IPAddress.TryParse(args[0], out ipAddress)) {
ip = args[0];
MessageBox.Show(args[0]);
}
using(Process process = Process.Start(client, "GameLaunching"))
{
while (process.MainWindowHandle == IntPtr.Zero && !process.HasExited)
Thread.Sleep(waitWindowSleep);
if (process.HasExited)
return;
for (int i = 0; i < maxTryCount; i++)
{
try
{
using (Injector injector = new Injector(process))
{
injector.EjectOnDispose = false;
injector.InjectLibrary(dll);
if (ip != IPAddress.Loopback.ToString())
injector.CallExport<IPInfo>(dll, "SetIP", new IPInfo(ip));
// Add any additional IPs you want maped here, you can also unmap them with UnMapIP if needed
//injector.CallExport<MapedIPInfo>(dll, "MapIP", new MapedIPInfo("RealGameIP", "YourServerIP"));
//injector.CallExport<MapedIPInfo>(dll, "UnMapIP", new MapedIPInfo("RealGameIP", "YourServerIP"));
return;
}
}
catch (Exception e)
{
Thread.Sleep(failInjectSleep);
MessageBox.Show(e.ToString());
}
}
}
MessageBox.Show("Failed to initialize GameLauncherEx");
}
[StructLayout(LayoutKind.Sequential)]
struct IPInfo
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]
public string IP;
public IPInfo(string ip)
{
IP = ip;
}
}
[StructLayout(LayoutKind.Sequential)]
struct MapedIPInfo
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]
public string DestIP;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]
public string IP;
public MapedIPInfo(string destIP, string ip)
{
DestIP = destIP;
IP = ip;
}
}
}
}
Injector.cs:
http://pastebin.com/QUVXSTHC
Imports.cs
http://pastebin.com/L1CtWYfN
I seemed to have surpassed the character limit, so I posted the code on pastebin.

Related

Cant join to multicast group c#

In my project I need receive a video through UDP. Source have a IP 224.0.0.21, Sink have a IP 169.254.170.141. I receive video through a port 3956 (This is a valid information from Wireshark). I use SharpPcap for receive UDP traffic, but it have not methods for join to multicast. I try this code from MSDN, but it dont work.
IPAddress multicastaddress = IPAddress.Parse("224.0.0.21");
IPEndPoint remoteep = new IPEndPoint(IPAddress.Any, 3956);
m_ClientTarget.JoinMulticastGroup(multicastaddress, localAddr);
In my PC I have some network adapters, but I use the IP address from device, that connected to source video. Source and sink connected directly. When I start monitor traffic in the wireshark my programm also receive packet, but without the wireshack it cant do it.
My code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SharpPcap;
using SharpPcap.LibPcap;
using SharpPcap.AirPcap;
using SharpPcap.WinPcap;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading;
namespace GVSPCapture
{
public partial class Form1 : Form
{
static int frameCounter = 0;
static byte[] pixels = new byte[1920 * 1080 * 3];
static IPAddress fpgaAddr = IPAddress.Parse("224.0.0.21");
static IPAddress localAddr = IPAddress.Parse("169.254.170.141");
static MulticastOption mcastOption = new MulticastOption(fpgaAddr, localAddr);
private static UdpClient m_ClientTarget = new UdpClient(3956);
private static IPAddress m_GrpAddr;
const int GroupPort = 3956;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
findDevices();
}
public void findDevices()
{
string ver = SharpPcap.Version.VersionString;
var devices = CaptureDeviceList.Instance;
foreach (var dev in devices)
{
lbxDevices.Items.Add(dev.Name + dev.Description);
}
}
private void JoinVideoMulticast()
{
IPAddress multicastaddress = IPAddress.Parse("224.0.0.21");
IPEndPoint remoteep = new IPEndPoint(IPAddress.Any, 3956);
m_ClientTarget.JoinMulticastGroup(multicastaddress, IPAddress.Parse("169.254.170.141"));
while (true)
{ }
}
private void startCapture(ICaptureDevice dev)
{
if (!dev.Started)
{
dev.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
int readTimeoutMilliseconds = 1000;
if (dev is AirPcapDevice)
{
// NOTE: AirPcap devices cannot disable local capture
var airPcap = dev as AirPcapDevice;
airPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp, readTimeoutMilliseconds);
}
else if (dev is WinPcapDevice)
{
var winPcap = dev as WinPcapDevice;
winPcap.Open(SharpPcap.WinPcap.OpenFlags.DataTransferUdp | SharpPcap.WinPcap.OpenFlags.NoCaptureLocal, readTimeoutMilliseconds);
}
else if (dev is LibPcapLiveDevice)
{
var livePcapDevice = dev as LibPcapLiveDevice;
livePcapDevice.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds);
}
else
{
throw new System.InvalidOperationException("unknown device type of " + dev.GetType().ToString());
}
dev.StartCapture();
Thread recvThread = new Thread(JoinVideoMulticast);
recvThread.Start();
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.tbxCnt.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.tbxCnt.Text = text;
}
}
private void device_OnPacketArrival(object sender, CaptureEventArgs e)
{
var time = e.Packet.Timeval.Date;
var len = e.Packet.Data.Length;
if (len == 572)
{
var tmp = e.Packet.Data;
int packet_id = tmp[47] << 16 | tmp[48] << 8 | tmp[49];
int startPos = (packet_id - 1) * 522;
for (int i = 50; i < tmp.Length; i+=3)
{
pixels[startPos + i + 0 - 50] = tmp[i];
pixels[startPos + i + 1 - 50] = tmp[i];
pixels[startPos + i + 2 - 50] = tmp[i];
}
}
if (len == 60)
{
var im = CopyDataToBitmap(pixels);
pictbFrame.Image = im;
frameCounter += 1;
SetText(frameCounter.ToString());
}
}
public Bitmap CopyDataToBitmap(byte[] data)
{
GCHandle pinned = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr ptr = pinned.AddrOfPinnedObject();
BitmapData dt = new BitmapData();
dt.Scan0 = ptr;
dt.Stride = 5760;
dt.Width = 1920;
dt.Height = 1080;
dt.PixelFormat = PixelFormat.Format24bppRgb;
Bitmap btm = new Bitmap(1920, 1080, 5760, PixelFormat.Format24bppRgb, dt.Scan0);
return btm;
}
private void btnStart_Click(object sender, EventArgs e)
{
int devNum = lbxDevices.SelectedIndex;
if (devNum > 0)
{
var device = CaptureDeviceList.Instance[devNum];
startCapture(device);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
int devNum = lbxDevices.SelectedIndex;
if (devNum > 0)
{
var device = CaptureDeviceList.Instance[devNum];
if (device.Started)
{
device.StopCapture();
device.Close();
}
}
m_ClientTarget.DropMulticastGroup(fpgaAddr);
}
}
}
Without seeing your code (I´m assuming that there´s more than the snippet you show) it´s difficult to help you.
A basic setup for a client receiving multicast datagrams would be something like this untested snippet:
UdpClient mClient = new UdpClient(3956, AddressFamily.InterNetwork);
IPAdress groupAddress = IPAddress.Parse("224.0.0.21);
mClient.JoinMulticastGroup(groupAddress);
After that you the receiving using mClient.Receive()...
Maybe this helps? Or the documentation on MSDN (https://msdn.microsoft.com/en-us/library/ekd1t784(v=vs.110).aspx).
C.
I tested the code with ffmpeg
ffmpeg.exe -i aa.mp4 -f mpeg udp://224.0.0.21:3956
int PORT = 3956;
string MULTICAST_IP = "224.0.0.21";
UdpClient udpClient = new UdpClient(PORT);
udpClient.JoinMulticastGroup(IPAddress.Parse(MULTICAST_IP));
var from = new IPEndPoint(0, 0);
var recvBuffer = udpClient.Receive(ref from);

C# 32feet.Net: Handling two bluetooth connections in seperate threads, gives SocketException

I'm writing a C# console application using the 32feet.Net library that creates two threads to search for and connect to different Bluetooth devices and then open up TCP sockets so that data can be passed to the devices via a network connection. I know this situation sounds completely bizarre, but I've been asked to do this by a senior colleague.
My code seems to work OK with only one device connected, although the Bluetooth connection does sometimes drop out after a couple of messages have been passed backwards and forwards. However, sometimes as soon as the second device connects I get an error saying System.net.sockets.socketexception a connection attempt failed because the connected party did not properly respond, other times the code just exits without throwing any exceptions.
I was wondering what is causing this, I've seen that the 32feet.Net library can support multiple connections. I'm wondering if I've made some errors, as I'm new to C#, .Net, and even Windows, and have never written any Bluetooth based code before.
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace BluetoothManager
{
class Program
{
static void Main(string[] args)
{
BTManager rover_btm = new BTManager();
BTManager base_btm = new BTManager();
base_btm.Port = 0xba5e;
rover_btm.Port = 17825;
base_btm.Name = "Base";
rover_btm.Name = "Rover";
base_btm.match = (args.Length >= 1 && args[0] != "") ? args[0] : "dev1";
rover_btm.match = (args.Length >= 2 && args[1] != "") ? args[1] : "dev2";
Console.WriteLine("Base Station match: " + base_btm.match);
Console.WriteLine("Rover match: " + rover_btm.match);
Thread Base = new Thread(new ThreadStart(base_btm.HandleThread));
Thread Rover = new Thread(new ThreadStart(rover_btm.HandleThread));
Base.Start();
Rover.Start();
Base.Join();
Rover.Join();
Console.Read();
}
}
}
BTManager.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Ports;
using InTheHand.Net.Sockets;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using Microsoft.Win32;
using System.IO;
namespace BluetoothManager
{
class BTManager
{
private static BluetoothDeviceInfo[] peers;
private BluetoothClient client;
private bool _isConnected = false;
private string _match;
private const string defpin = "0000";
private TcpListener tcpListener;
private int _port;
private string _name = "Not Named";
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Port
{
get { return _port; }
set { _port = value; }
}
public bool IsConnected
{
get { return _isConnected; }
private set { _isConnected = value; }
}
public string match
{
get { return _match; }
set { _match = value; }
}
public BTManager()
{
client = new BluetoothClient();
}
public void HandleThread()
{
BluetoothDeviceInfo device;
while (!this.findDevice(out device)) ;
Console.WriteLine("About to pair");
int count = 0;
int max = 5;
while ((!(BluetoothSecurity.PairRequest(device.DeviceAddress, defpin))) && count < max)
{
Console.WriteLine("Pairing Failed, retrying");
count++;
Thread.Sleep(100);
}
if (count == max)
{
HandleThread();
}
else
{
Console.WriteLine("Paired..Beginning connect");
client.BeginConnect(device.DeviceAddress, BluetoothService.SerialPort, this.callback, client);
}
}
private void callback(IAsyncResult result)
{
client.EndConnect(result);
this.tcpListener = new TcpListener(IPAddress.Loopback, _port);
this.tcpListener.Start();
TcpClient TcpClient = this.tcpListener.AcceptTcpClient();
NetworkStream networkStream = TcpClient.GetStream();
Stream bluetoothStream = client.GetStream();
byte[] fromNetwork = new byte[1024];
byte[] fromBluetooth = new byte[1024];
while (client.Connected && TcpClient.Connected)
{
try
{
if (networkStream.CanRead)
{
Array.Clear(fromNetwork, 0, 1024);
networkStream.Read(fromNetwork, 0, 1024);
Console.WriteLine(Encoding.ASCII.GetString(fromNetwork));
bluetoothStream.Write(fromNetwork, 0, 1024);
bluetoothStream.Flush();
while (bluetoothStream.CanRead)
{
Array.Clear(fromBluetooth, 0, 1024);
bluetoothStream.Read(fromBluetooth, 0, 1024);
Console.WriteLine(Encoding.ASCII.GetString(fromNetwork));
networkStream.Write(fromBluetooth, 0, 1024);
networkStream.Flush();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
this.HandleThread();
}
private bool findDevice(out BluetoothDeviceInfo device)
{
peers = client.DiscoverDevicesInRange();
device = Array.Find(peers, element => element.DeviceName == match);
foreach (BluetoothDeviceInfo btdi in peers)
{
Console.WriteLine(btdi.DeviceName);
}
if (device == null)
{
Console.WriteLine(Name +": Not Found");
return false;
}
else
{
Console.WriteLine(Name +": Found");
return true;
}
}
}
}
I am using Sockets in order to communicate with the Bluetooth device.
Its very important to release any resources when disconnecting.
In order to find your COM port you can use this link
Your stream is located here:
System.Net.Sockets.NetworkStream stream = bthClient.GetStream();
Example to how to connect and find your device.
private InTheHand.Net.Sockets.BluetoothClient _BTClient = null;
private InTheHand.Net.Sockets.BluetoothDeviceInfo[] _clientDevices;
/// <summary>
/// Thread function to discover devices
/// </summary>
private void DiscoverBluetoothThread()
{
try
{
_BTClient = new InTheHand.Net.Sockets.BluetoothClient();
_clientDevices = _BTClient.DiscoverDevices(999, _authenticated, _remembered, _unknown);
_BTClient.Dispose();
_BTClient = null;
}
catch (Exception) { }
}
Private void Connect(InTheHand.Net.Sockets.BluetoothDeviceInfo info)
{
string addressN = info.DeviceAddress.ToString("N"); //Format Example: "00066606E014"
string addressC = info.DeviceAddress.ToString("C"); //Format Example: "00:06:66:06:E0:14"
string addressP = info.DeviceAddress.ToString("P"); //Format Example: "00.06.66.06.E0.14"
string addressD = info.DeviceAddress.ToString(); //Format Example: "00066606E014"
string serialPort = FindBluetoothPortName(addressN);
//https://stackoverflow.com/questions/26439091/how-to-get-bluetooth-device-com-serial-port-in-winform-c/27919129#27919129
if (string.IsNullOrEmpty(serialPort) == false && serialPort.Trim().Length > "COM".Length)
bool installed = InstallBluetoothDevice(addressC, passKey, autoConnect);
}
public bool InstallBluetoothDevice(string deviceMACAddress, string passKey, bool connect)
{
string strDevicePassKey = passKey;
string BTMac = deviceMACAddress;
InTheHand.Net.BluetoothAddress BTAddress;
InTheHand.Net.Sockets.BluetoothClient BTClient = new InTheHand.Net.Sockets.BluetoothClient();
InTheHand.Net.BluetoothEndPoint BTEndPoint;
InTheHand.Net.Bluetooth.BluetoothRadio BTRadio;
BTRadio = InTheHand.Net.Bluetooth.BluetoothRadio.PrimaryRadio;
BTRadio.Mode = RadioMode.Connectable;
Guid spguid = BluetoothService.SerialPort;
BTAddress = InTheHand.Net.BluetoothAddress.Parse(BTMac);
BTEndPoint = new InTheHand.Net.BluetoothEndPoint(BTAddress, spguid);
try
{
BluetoothSecurity.PairRequest(BTAddress, strDevicePassKey);
//Application.DoEvents();
BTClient = new InTheHand.Net.Sockets.BluetoothClient();
if (connect)
{
BTClient.Connect(BTEndPoint);
BTEndPoint = new InTheHand.Net.BluetoothEndPoint(BTAddress, spguid);
_connectedDevices.Add(BTAddress, BTClient);
return BTClient.Connected;
}
return true;
}
catch (Exception ex)
{
return false;
}
}

unable to refresh windows after setting the global proxy settings

I'm trying to enable/disable the windows global proxy( in Internet option ) using windows registry. If I set the value, I don't have any problems but refreshing the settings. After searching I found a question on SO that provided the code for that. But now the problem is that In each session of the app it works only once. i.e. it works the first time and if you want it to work again, you have to rerun the app. Any ideas what could be the problem??? here's the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
namespace SystemProxyToggle
{
public partial class Form1 : Form
{
[DllImport("wininet.dll")]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
public const int INTERNET_OPTION_REFRESH = 37;
static bool settingsReturn, refreshReturn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
queryStatus();
}
private void btnToggle_Click(object sender, EventArgs e)
{
toggleStatus();
queryStatus();
}
private void queryStatus()
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
int status = (int)registry.GetValue("ProxyEnable");
if (status == 0)
{
lblStatus.Text = "Proxy Is Disabled";
lblStatus.ForeColor = Color.Maroon;
}
else
{
lblStatus.Text = "Proxy Is Enabled";
lblStatus.ForeColor = Color.Green;
}
//I added this after I encountered the problem
//though I don't that this is the problem
registry.Close();
}
private void toggleStatus()
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
int status = (int)registry.GetValue("ProxyEnable");
if (status == 1)
{
registry.SetValue("ProxyEnable", 0);
}
else
{
registry.SetValue("ProxyEnable", 1);
}
//Refresh System Settings
settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
//I added this after I encountered the problem
registry.Close();
}
}
}
I've tested this code in Windows 7 (Internet Explorer 11) and had no problems, but when I tried in a second system with Windows 8, I had the same result as you did.
After digging for a while I found out that you should call InternetSetOption differently, basically like this:
INTERNET_OPTION_PROXY_SETTINGS_CHANGED = 95
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_SETTINGS_CHANGED, IntPtr.Zero, 0);
I tried it again on both systems and it worked just fine.
Cheers
For anybody else stuck on this issue, something odd seemed to do the trick for me.
I simply removed/commented all calls to InternetSetOption()
//settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
//refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
Restarted the program and this time the registry changes took effect in both directions as long as I wanted and not just the first time.

Website Visitor (Visited URL) Logger Application

I have made an application to log all websites visited by current PC user. This is not for a malicious use. I am making this feature for my employee monitoring software which will be licensed under proper laws.
Coming on main point, Whenever I am fetching URL from any browser such as IE. I am only getting its URL for all opened tabs. I am unable to get any tab handle for IE7+ , because of which I am unable to maintain a list of tabs for which I have already logged URL's for same tab.
Below is my code (Take a Look on Commented Code First):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace WebsiteLoggerConsole
{
public class WebLogger
{
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent,
IntPtr hwndChildAfter,
string lpszClass,
string lpszWindow);
System.Threading.Timer log;
public void StartLoggin()
{
try
{
TimerCallback logcallback = new TimerCallback(LogTick);
log = new System.Threading.Timer(logcallback, null, 0, 2000);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
}
}
public void StopLogging()
{
try
{
log.Dispose();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
}
}
public void LogTick(Object stateInfo)
{
CreateLog();
}
void CreateLog()
{
try
{
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
string filename;
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if (filename.Equals("iexplore"))
{
int val = ie.HWND;
IntPtr hwnd = new IntPtr(val);
IntPtr uihwnd = GetDirectUIHWND(hwnd);
string ddd = (ie.LocationURL) + " :::: " + (uihwnd.ToString());
Console.WriteLine(ddd);
}
}
//SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
//string filename;
//foreach (SHDocVw.InternetExplorer ie in shellWindows)
//{
// filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
// if (filename.Equals("iexplore"))
// {
// int val = ie.HWND;
// IntPtr hwnd = new IntPtr(val);
// IntPtr uihwnd = GetDirectUIHWND(hwnd);
// IntPtr tabhwnd = GetDirectUIHWND(uihwnd);
// string ddd = (ie.LocationURL) + " :::: " + (tabhwnd.ToString());
// Console.WriteLine(ddd);
// }
//}
//Process[] processlist = Process.GetProcesses();
//foreach (Process theprocess in processlist)
//{
// if (theprocess.ProcessName == "iexplore")
// {
// Console.WriteLine("Process: {0}, ID: {1}, Handle: {3}, Window name: {2}",
// theprocess.ProcessName, theprocess.Id, theprocess.MainWindowTitle, theprocess.SessionId.ToString()
// );
// }
//}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
}
}
private static IntPtr GetDirectUIHWND(IntPtr ieFrame)
{
// try IE 9 first:
IntPtr intptr = FindWindowEx(ieFrame, IntPtr.Zero, "WorkerW", null);
if (intptr == IntPtr.Zero)
{
// IE8 and IE7
intptr = FindWindowEx(ieFrame, IntPtr.Zero, "CommandBarClass", null);
}
intptr = FindWindowEx(intptr, IntPtr.Zero, "ReBarWindow32", null);
//intptr = FindWindowEx(intptr, IntPtr.Zero, "TabBandClass", null);
//intptr = FindWindowEx(intptr, IntPtr.Zero, "DirectUIHWND", null);
return intptr;
}
}
}
I provided a solution on this topic: How to write a standalone URL logger for Windows?
There I used Java, but you can do the same by using C#. I am almost sure there is a lot of good libpcap wrappers for C#.
There is a project called pcapDotNet and you can use it.
Adjusting one example:
using System;
using System.Collections.Generic;
using PcapDotNet.Core;
using PcapDotNet.Packets;
using PcapDotNet.Packets.IpV4;
using PcapDotNet.Packets.Transport;
namespace InterpretingThePackets
{
class Program
{
static void Main(string[] args)
{
// Retrieve the device list from the local machine
IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
if (allDevices.Count == 0)
{
Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
return;
}
// Print the list
for (int i = 0; i != allDevices.Count; ++i)
{
LivePacketDevice device = allDevices[i];
Console.Write((i + 1) + ". " + device.Name);
if (device.Description != null)
Console.WriteLine(" (" + device.Description + ")");
else
Console.WriteLine(" (No description available)");
}
int deviceIndex = 0;
do
{
Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
string deviceIndexString = Console.ReadLine();
if (!int.TryParse(deviceIndexString, out deviceIndex) ||
deviceIndex < 1 || deviceIndex > allDevices.Count)
{
deviceIndex = 0;
}
} while (deviceIndex == 0);
// Take the selected adapter
PacketDevice selectedDevice = allDevices[deviceIndex - 1];
// Open the device
using (PacketCommunicator communicator =
selectedDevice.Open(65536, // portion of the packet to capture
// 65536 guarantees that the whole packet will be captured on all the link layers
PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
1000)) // read timeout
{
// Check the link layer. We support only Ethernet for simplicity.
if (communicator.DataLink.Kind != DataLinkKind.Ethernet)
{
Console.WriteLine("This program works only on Ethernet networks.");
return;
}
// Compile the filter
using (BerkeleyPacketFilter filter = communicator.CreateFilter("ip and tcp"))
{
// Set the filter
communicator.SetFilter(filter);
}
Console.WriteLine("Listening on " + selectedDevice.Description + "...");
// start the capture
communicator.ReceivePackets(0, PacketHandler);
}
}
// Callback function invoked by libpcap for every incoming packet
private static void PacketHandler(Packet packet)
{
// print timestamp and length of the packet
Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);
IpV4Datagram ip = packet.Ethernet.IpV4;
//Do your magic here using HttpRequestDatagram
}
}
}

Register and unregister OCX dll

Why Register a DLL?
I have a lot of basic doubts on DLLs and i have tried to put them in a listed Questions form as below:
Why do we need to register a DLL?
What happens when we register a DLL?
When i use a "LoadLibrary" in my C# code, i do not do any registration.
Whats the connection/difference between the two?
(Registering a DLL and Loading a DLL)
Can i register all the DLLs? or are there some DLLs which cannot be registered and why?
If anyone can recommend some online articles for clarifying my doubts it would be big help!
otherwise snippet code.
im using this code but it doesnt give exactly what i need, thats why i asked here....
its working fine in 32-bit machine but it gives denied path error in 64 bit machine
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security;
using System.Management;
using System.IO;
using CCC_DLLRegistar.LoadLibrary;
using System.Security.Principal;
using System.Diagnostics;
namespace CCC_DLLRegistar
{
public partial class Form1 : Form
{
#region Is64BitOperatingSystem (IsWow64Process)
public static bool Is64BitOperatingSystem()
{
if (IntPtr.Size == 8) // 64-bit programs run only on Win64
{
return true;
}
else // 32-bit programs run on both 32-bit and 64-bit Windows
{
// Detect whether the current process is a 32-bit process
// running on a 64-bit system.
bool flag;
return ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") &&
IsWow64Process(GetCurrentProcess(), out flag)) && flag);
}
}
static bool DoesWin32MethodExist(string moduleName, string methodName)
{
IntPtr moduleHandle = GetModuleHandle(moduleName);
if (moduleHandle == IntPtr.Zero)
{
return false;
}
return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero);
}
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule,
[MarshalAs(UnmanagedType.LPStr)]string procName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
#endregion
#region Is64BitOperatingSystem (WMI)
public static bool Is64BitOperatingSystem(string machineName,
string domain, string userName, string password)
{
ConnectionOptions options = null;
if (!string.IsNullOrEmpty(userName))
{
options = new ConnectionOptions();
options.Username = userName;
options.Password = password;
options.Authority = "NTLMDOMAIN:" + domain;
}
// Else the connection will use the currently logged-on user
// Make a connection to the target computer.
ManagementScope scope = new ManagementScope("\\\\" +
(string.IsNullOrEmpty(machineName) ? "." : machineName) +
"\\root\\cimv2", options);
scope.Connect();
ObjectQuery query = new ObjectQuery(
"SELECT AddressWidth FROM Win32_Processor");
// Perform the query and get the result.
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject queryObj in queryCollection)
{
if (queryObj["AddressWidth"].ToString() == "64")
{
return true;
}
}
return false;
}
#endregion
public Form1()
{
InitializeComponent();
}
private string _RootPath = string.Empty;
private string _path = string.Empty;
private List<string> _Regfiles;
DLLHelper obj;
public string path
{
get { return _path; }
set { _path = value; }
}
public string RootPath
{
get { return _RootPath; }
set { _RootPath = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
// Solution 1. Is64BitOperatingSystem (IsWow64Process)
// Determine whether the current operating system is a 64 bit
// operating system.
bool f64bitOS = Is64BitOperatingSystem();
//Console.WriteLine("The current operating system {0} 64-bit.",
// f64bitOS ? "is" : "is not");
// Solution 2. Is64BitOperatingSystem (WMI)
// Determine whether the current operating system is a 64 bit
// operating system through WMI. The function is also able to
// query the bitness of OS on a remote machine.
try
{
f64bitOS = Is64BitOperatingSystem(".", null, null, null);
//Console.WriteLine("The current operating system {0} 64-bit.",
// f64bitOS ? "is" : "is not");
if (f64bitOS == true)
{
RootPath = "C:\\windows\\SysWow64\\";
}
else
{
RootPath = "C:\\Windows\\System32\\";
}
bool isAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent())
.IsInRole(WindowsBuiltInRole.Administrator) ? true : false;
if (isAdmin)
{
MessageBox.Show("you are an administrator");
}
else
{
MessageBox.Show("You are not an administrator");
}
path = Application.StartupPath + "\\CCC DLL\\";
List<string> regsvr = new List<string>();
foreach (string s in Directory.GetFiles(path, "*.*").Select(Path.GetFileName))
{
regsvr.Add(Application.StartupPath + "\\CCC DLL\\" + s);
}
foreach (string filepath in regsvr)
{
Registar_Dlls(filepath);
}
_Regfiles=new List<string>();
foreach (string s in Directory.GetFiles(path, "*.dll").Select(Path.GetFileName))
{
_Regfiles.Add(Application.StartupPath + "\\CCC DLL\\" + s);
if (DLLHelper.UnmanagedDllIs64Bit(Application.StartupPath + "\\CCC DLL\\" + s) == true)
{
MessageBox.Show("62 bit");
}
else
{
MessageBox.Show("32 bit");
}
}
foreach (string s in Directory.GetFiles(path, "*.ocx").Select(Path.GetFileName))
_Regfiles.Add(Application.StartupPath + "\\CCC DLL\\" + s);
foreach (string filepath in _Regfiles)
{
obj = new DLLHelper(filepath);
obj.DumpToFile(RootPath + obj.GetDLLName());
}
MessageBox.Show("Register Colmpleted");
}
catch (Exception ex)
{
//Console.WriteLine("Is64BitOperatingSystem throws the exception: {0}",
// ex.Message);
MessageBox.Show(ex.Message.ToString());
}
}
public void Registar_Dlls(string filePath)
{
try
{
//'/s' : Specifies regsvr32 to run silently and to not display any message boxes.
//string arg_fileinfo = "/s" + " " + "\"" + filePath + "\"";
string arg_fileinfo = RootPath +"\regsvr32.exe"+" "+ "/s" + " " + "\"" + filePath;
Process reg = new Process();
//This file registers .dll files as command components in the registry.
reg.StartInfo.FileName = "cmd.exe"; //"regsvr32.exe";
reg.StartInfo.Arguments = arg_fileinfo;
reg.StartInfo.UseShellExecute = false;
reg.StartInfo.CreateNoWindow = true;
reg.StartInfo.RedirectStandardOutput = true;
if (System.Environment.OSVersion.Version.Major >= 6)
{
reg.StartInfo.Verb = "runas";
}
reg.Start();
reg.WaitForExit();
reg.Close();
// MessageBox.Show("Successfully Registered your Ocx files");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

Categories