Archive for March, 2009

31
Mar
09

[Javascript] Number Format String (1)

Ive been set a mission to make 3, different, functions to format a number with commas, e.g. 12345 = 12,345; 1234567890 = 1,234,567,890

Here is number one:

function numberFormat_1(text) {
	//Reverse string
	//Loop through adding every character
	//If index = 3, add a comma
	//Reverse string
	text = text.split("").reverse().join("");
	var output = "";
	var j=0;
	for(var i = 0;i<text.length;i++) {
		output += text.charAt(i);
		j++;
		if(j==3 && i != text.length-1) {
			output += ",";
			j=0;
		}
	}
	output = output.split("").reverse().join("");
	return output;
}

Usage:

	var text = "123456789123456789";
	text = numberFormat_1(text);
	alert(text);

Would Output:

123,456,789,123,456,789

Advertisements
30
Mar
09

[VB.Net] GetPixelColourCount

Decided to turn my solution to the question here into an easy to use function.
It uses the goto function, which I feel is frowned upon, but go ahead and complain ^_^

    ''' <summary >
    ''' Function to count the number of pixels of the same colour
    ''' </summary >
    ''' <param name="bmpImage" > The image as a Bitmap that you wish to count the pixels of</param >
    ''' <param name="Bounds" > The rectangle for the area that you wish to calculate</param >
    ''' <returns > A list of strings containing the pixels colour and the number of pixels of that colour</returns >
    ''' <remarks > sim0n</remarks >
    Private Function GetPixelColourCount(ByVal bmpImage As Bitmap, ByVal Bounds As RectangleF) As List(Of String())
        Dim Pixels As New List(Of String())
        For x As Integer = Bounds.Left To Bounds.Right - 1
            For y As Integer = Bounds.Top To Bounds.Bottom - 1
                Dim Found As Boolean = False
                For Each str As String() In Pixels
                    If str(0) = CStr(bmpImage.GetPixel(x, y).ToArgb) Then
                        str(1) = CStr(CInt(str(1)) + 1)
                        Found = True
                        GoTo pixelFound
                    End If
                Next
                Pixels.Add(New String() {CStr(bmpImage.GetPixel(x, y).ToArgb), 1})
pixelFound:
            Next
        Next
        Return Pixels
    End Function

Usage:
Using image: http://privatewww.essex.ac.uk/~sjs/research/iso_colour_blocks.png

        ''Get our image from PictureBox1
        Dim btmp As New Bitmap(PictureBox1.Image)
        ''Set the cursor to wait
        Me.Cursor = Cursors.WaitCursor
        ''Loop through the results - Rectangle is the entire image
        For Each str As String() In GetPixelColourCount(btmp, New RectangleF(0, 0, btmp.PhysicalDimension.Width, btmp.PhysicalDimension.Height))
            Debug.WriteLine(Color.FromArgb(str(0)).ToString & " | Count: " & str(1))
        Next
        ''Reset Cursor
        Me.Cursor = Cursors.Default

Would output:
Color [A=255, R=85, G=85, B=85] | Count: 65536
Color [A=255, R=0, G=255, B=0] | Count: 32768
Color [A=255, R=127, G=0, B=128] | Count: 32768
Color [A=255, R=0, G=0, B=255] | Count: 32768
Color [A=255, R=127, G=128, B=0] | Count: 32768
Color [A=255, R=255, G=0, B=0] | Count: 32768
Color [A=255, R=0, G=127, B=128] | Count: 32768

You can also just select regions of the image to calculate using the Bounds parameter, for example to get the colour of just one square, you could do:

  ''64 Pixels along
  ''0 Pixels down
  ''Width 64 pixels
  ''Heigh 64 Pixels
  For Each str As String() In GetPixelColourCount(btmp, New RectangleF(64, 0, 64, 64))
      Debug.WriteLine(Color.FromArgb(str(0)).ToString & " | Count: " & str(1))
  Next

Would output:
Color [A=255, R=127, G=128, B=0] | Count: 4096

30
Mar
09

[VB.Net] Q: Get the amount and colour of pixels in an Image

The question asked “How do i get the amount and colour of pixels in an Image?”

The Solution
I had to think a bit about this one, dealing with image processing needs to be as efficent as possible, however I couldnt see a better way than just looping through the pixels and adding them to a list.
Here is the solution that I posted to the users project:

    Dim PixelList As New List(Of String())

    Public Sub ColourInList(ByVal Colour As Color)
        Dim Found As Boolean = False
        For Each str As String() In PixelList
            If str(0) = CStr(Colour.ToArgb) Then
                str(1) = CStr(CInt(str(1)) + 1)
                Found = True
                Exit For
            End If
        Next
        If Found = False Then PixelList.Add(New String() {CStr(Colour.ToArgb), 1})
    End Sub

    Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
        Dim btmp As New Bitmap(PictureBox1.Image)
        For x As Integer = 0 To btmp.Width - 1
            For y As Integer = 0 To btmp.Height - 1
                ColourInList(btmp.GetPixel(x, y))
            Next
        Next
        For Each str As String() In PixelList
            Debug.WriteLine(Color.FromArgb(str(0)).ToString & " | Count: " & str(1))
        Next
    End Sub

Would Output:
Using this Image:
http://privatewww.essex.ac.uk/~sjs/research/iso_colour_blocks.png

Color [A=255, R=85, G=85, B=85] | Count: 65536
Color [A=255, R=0, G=255, B=0] | Count: 32768
Color [A=255, R=127, G=0, B=128] | Count: 32768
Color [A=255, R=0, G=0, B=255] | Count: 32768
Color [A=255, R=127, G=128, B=0] | Count: 32768
Color [A=255, R=255, G=0, B=0] | Count: 32768
Color [A=255, R=0, G=127, B=128] | Count: 32768

29
Mar
09

[C++] Creating a Window from a DLL

Currently I’ve been working on a project that requires me to inject a DLL to an external program, and create a window under that process.
Looking on the web, there are really very few resources explaining how to do this.

I don’t know if this is the ‘correct’ way to do this, but it works.
The basic idea behind it:

  • On inject
    • Create new thread
  • On new thread
    • Register window class
    • CreateWindowEx + ShowWindow
    • GetMessage and send them to a WndProc

Right so, starting off.
Create a new Windows DLL and add windows.h as an include
Now on the DLLMain, the entrypoint for the DLL, you want to add the code to create a new thread:

BOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call,LPVOID lpReserved)
{
	if(ul_reason_for_call==DLL_PROCESS_ATTACH) {
		inj_hModule = hModule;
		CreateThread(0, NULL, ThreadProc, (LPVOID)L"Window Title", NULL, NULL);
	}
	return TRUE;
}

Im passing our new windows title as the lParam for the tread, this is not necessary – and in this situation, silly.
Now we have a new thread, which has its start routine at ThreadProc
You will also need to create a new variable where we can store our modules handle:

HINSTANCE  inj_hModule;          //Injected Modules Handle

So now, lets set up our window.
We are going to create a function to register our window:

BOOL RegisterDLLWindowClass(wchar_t szClassName[])
{
    WNDCLASSEX wc;
    wc.hInstance =  inj_hModule;
    wc.lpszClassName = (LPCWSTR)szClassName;
    wc.lpfnWndProc = DLLWindowProc;
    wc.style = CS_DBLCLKS;
    wc.cbSize = sizeof (WNDCLASSEX);
    wc.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wc.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor (NULL, IDC_ARROW);
    wc.lpszMenuName = NULL;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hbrBackground = (HBRUSH) COLOR_BACKGROUND;
    if (!RegisterClassEx (&wc))
		return 0;
}

This function will register whatever class name is passed to it, again, in this situation it is unnecessary, you could just write:

wc.lpszClassName = (LPCWSTR)L"InjectedDLLWindowClass";

Now, we are going to make a function to create a menu for our window, to check that the messages are being received
Firstly, define two IDs for our menu

#define MYMENU_EXIT         (WM_APP + 101)
#define MYMENU_MESSAGEBOX   (WM_APP + 102)

Now the code for creating menus is fairly simple, we will just create 2 basic popup menus with two test buttons on, one to close the window, and one to display a messagebox.

HMENU CreateDLLWindowMenu()
{
	HMENU hMenu;
	hMenu = CreateMenu();
	HMENU hMenuPopup;
	if(hMenu==NULL)
           return FALSE;
	hMenuPopup = CreatePopupMenu();
	AppendMenu (hMenuPopup, MF_STRING, MYMENU_EXIT, TEXT("Exit"));
	AppendMenu (hMenu, MF_POPUP, (UINT_PTR) hMenuPopup, TEXT("File")); 

	hMenuPopup = CreatePopupMenu();
	AppendMenu (hMenuPopup, MF_STRING,MYMENU_MESSAGEBOX, TEXT("MessageBox")); 
	AppendMenu (hMenu, MF_POPUP, (UINT_PTR) hMenuPopup, TEXT("Test")); 
	return hMenu;
}

That returns a handle to our new menu, which we can pass to the CreateWindowEx function.
So, now lets deal with out ThreadProc, the start routine for the thread.
To begin with, I cast the lParam from a LPVOID – which contains our window name – back to a wchar_t
I then use the CreateDLLWindowMenu function and RegisterDLLWindowClass to be used in CreateWindowEx
Then just create the window, show it and handle the messages:

DWORD WINAPI ThreadProc( LPVOID lpParam )
{
	MSG messages;
	wchar_t *pString = reinterpret_cast<wchar_t * > (lpParam);
	HMENU hMenu = CreateDLLWindowMenu();
	RegisterDLLWindowClass(L"InjectedDLLWindowClass");
	prnt_hWnd = FindWindow(L"Window Injected Into ClassName", L"Window Injected Into Caption");
	HWND hwnd = CreateWindowEx (0, L"InjectedDLLWindowClass", pString, WS_EX_PALETTEWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 400, 300, prnt_hWnd, hMenu,inj_hModule, NULL );
	ShowWindow (hwnd, SW_SHOWNORMAL);
	while (GetMessage (&messages, NULL, 0, 0))
	{
		TranslateMessage(&messages);
        	DispatchMessage(&messages);
	}
	return 1;
}

Since I wanted this window to have a parent, I used FindWindow to locate the handle, and passed that to the CreateWindowEx, you would need to add another HWND to your globals:

HWND       prnt_hWnd;            //Parent Window Handle

Now we need to set up our WndProc for the new window, this is stated in the RegisterDLLWindowClass:

wc.lpfnWndProc = DLLWindowProc;

So we create the WndProc and handle the messages that we will receive from the Menu (Exit and MessageBox)

LRESULT CALLBACK DLLWindowProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
		case WM_COMMAND:
               switch(wParam)
               {
                    case MYMENU_EXIT:
						SendMessage(hwnd, WM_CLOSE, 0, 0);
                        break;
                    case MYMENU_MESSAGEBOX:
						MessageBox(hwnd, L"Test", L"MessageBox",MB_OK);
                        break;
               }
               break;
		case WM_DESTROY:
			PostQuitMessage (0);
			break;
		default:
			return DefWindowProc (hwnd, message, wParam, lParam);
    }
    return 0;
}

Now if you were to inject this DLL into another process, you would get something that looked like this:
injectedwindow

Below is the complete code listing.
Continue reading ‘[C++] Creating a Window from a DLL’

28
Mar
09

[VB.Net] GetWindowPos

I wrote this function a while back, but its often quite useful, so I thought that I would post it back up here.
Its basically the equivalent of the SetWindowPos API, which is used for setting various properties of a window.
This function is slightly edited from the one previously posted, which had an error in the size calculation and this also uses the .net Point and Rectangle structures

    Private Declare Function GetNextWindow Lib "user32" Alias "GetWindow" (ByVal hwnd As IntPtr, ByVal wFlag As Integer) As IntPtr
    Private Declare Function GetWindowPlacement Lib "user32" (ByVal hwnd As IntPtr, ByRef lpwndpl As WINDOWPLACEMENT) As Integer

    Private Structure WINDOWPLACEMENT
        Public Length As Integer
        Public flags As Integer
        Public showCmd As Integer
        Public ptMinPosition As Point
        Public ptMaxPosition As Point
        Public rcNormalPosition As Rectangle
    End Structure

    Public Enum WNDSTATE
        SW_HIDE = 0
        SW_SHOWNORMAL = 1
        SW_NORMAL = 1
        SW_SHOWMINIMIZED = 2
        SW_MAXIMIZE = 3
        SW_SHOWNOACTIVATE = 4
        SW_SHOW = 5
        SW_MINIMIZE = 6
        SW_SHOWMINNOACTIVE = 7
        SW_SHOWNA = 8
        SW_RESTORE = 9
        SW_SHOWDEFAULT = 10
        SW_MAX = 10
    End Enum

    Private Const GW_HWNDNEXT = 2
    Private Const GW_HWNDPREV = 3

    ''' <summary >
    ''' Return values from equivalent to those in the SetWindowPos API
    ''' </summary >
    ''' <param name="hwnd" > In - The handle of the window you wish to get the information from</param >
    ''' <param name="ptrPhwnd" > Out - Returns the handle of the previous window in the Z order</param >
    ''' <param name="ptrNhwnd" > Out - Returns the handle of the next window in the Z order</param >
    ''' <param name="ptPoint" > Out - Returns the location of the specified window on the screen</param >
    ''' <param name="szSize" > Out - Returns the size of the specified window</param >
    ''' <param name="intShowCmd" > Out - Returns the state of the window, returns a WNDSTATE value</param >
    ''' <remarks > If you use the function on a control, it will return the handles for the buttons next in the forms Z order.
    ''' If the handle passed for hwnd is invalid, the function will return 0 for all values</remarks >
    Public Sub GetWindowPos(ByVal hwnd As Integer, ByRef ptrPhwnd As Integer, ByRef ptrNhwnd As Integer, ByRef ptPoint As Point, ByRef szSize As Size, ByRef intShowCmd As WNDSTATE)
        Dim wInf As WINDOWPLACEMENT
        wInf.Length = System.Runtime.InteropServices.Marshal.SizeOf(wInf)
        GetWindowPlacement(hwnd, wInf)
        szSize = New Size(wInf.rcNormalPosition.Right - (wInf.rcNormalPosition.Left * 2), wInf.rcNormalPosition.Bottom - (wInf.rcNormalPosition.Top * 2))
        ptPoint = New Point(wInf.rcNormalPosition.Left, wInf.rcNormalPosition.Top)
        ptrPhwnd = GetNextWindow(hwnd, GW_HWNDPREV)
        ptrNhwnd = GetNextWindow(hwnd, GW_HWNDNEXT)
        intShowCmd = wInf.showCmd
    End Sub

Usage:

        Dim hwnd As Integer = Process.GetProcessesByName("calc")(0).MainWindowHandle
        Dim ptrPhwnd, ptrNhwnd As Integer
        Dim ptPoint As Point
        Dim szSize As Size
        Dim intShowCmd As WNDSTATE
        GetWindowPos(hwnd, ptrPhwnd, ptrNhwnd, ptPoint, szSize, intShowCmd)
        Debug.WriteLine("Window Handle: " & hwnd)
        Debug.WriteLine("Previous Window Handle: " & ptrPhwnd)
        Debug.WriteLine("Next Window Handle: " & ptrNhwnd)
        Debug.WriteLine("Window Location: (" & ptPoint.X & ", " & ptPoint.Y & ")")
        Debug.WriteLine("Window Size - Width: " & szSize.Width & " Height: " & szSize.Height)
        Debug.WriteLine("Window State: " & intShowCmd.ToString)

Would output:

Window Handle: 4065694
Previous Window Handle: 8194392
Next Window Handle: 263910
Window Location: (2934, 89)
Window Size – Width: 480 Height: 310
Window State: SW_NORMAL

28
Mar
09

[VB.net] Keyboard Hook Class

The keyboard hook from my old blog; “Low Level Keyboard Hook (Global) – Installing a Low Level Keyboard Hook”
This version is slightly updated, to cast the vkCode to the .net Keys enum to make key handling easier.

[16 June 2011 complete rewrite – should now work on every system -_-]

Imports System.Runtime.InteropServices

Public Class KeyboardHook

    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
    Private Overloads Shared Function SetWindowsHookEx(ByVal idHook As Integer, ByVal HookProc As KBDLLHookProc, ByVal hInstance As IntPtr, ByVal wParam As Integer) As Integer
    End Function
    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
    Private Overloads Shared Function CallNextHookEx(ByVal idHook As Integer, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
    End Function
    <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _
    Private Overloads Shared Function UnhookWindowsHookEx(ByVal idHook As Integer) As Boolean
    End Function

    <StructLayout(LayoutKind.Sequential)> _
    Private Structure KBDLLHOOKSTRUCT
        Public vkCode As UInt32
        Public scanCode As UInt32
        Public flags As KBDLLHOOKSTRUCTFlags
        Public time As UInt32
        Public dwExtraInfo As UIntPtr
    End Structure

    <Flags()> _
    Private Enum KBDLLHOOKSTRUCTFlags As UInt32
        LLKHF_EXTENDED = &H1
        LLKHF_INJECTED = &H10
        LLKHF_ALTDOWN = &H20
        LLKHF_UP = &H80
    End Enum

    Public Shared Event KeyDown(ByVal Key As Keys)
    Public Shared Event KeyUp(ByVal Key As Keys)

    Private Const WH_KEYBOARD_LL As Integer = 13
    Private Const HC_ACTION As Integer = 0
    Private Const WM_KEYDOWN = &H100
    Private Const WM_KEYUP = &H101
    Private Const WM_SYSKEYDOWN = &H104
    Private Const WM_SYSKEYUP = &H105

    Private Delegate Function KBDLLHookProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer

    Private KBDLLHookProcDelegate As KBDLLHookProc = New KBDLLHookProc(AddressOf KeyboardProc)
    Private HHookID As IntPtr = IntPtr.Zero

    Private Function KeyboardProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
        If (nCode = HC_ACTION) Then
            Dim struct As KBDLLHOOKSTRUCT
            Select Case wParam
                Case WM_KEYDOWN, WM_SYSKEYDOWN
                    RaiseEvent KeyDown(CType(CType(Marshal.PtrToStructure(lParam, struct.GetType()), KBDLLHOOKSTRUCT).vkCode, Keys))
                Case WM_KEYUP, WM_SYSKEYUP
                    RaiseEvent KeyUp(CType(CType(Marshal.PtrToStructure(lParam, struct.GetType()), KBDLLHOOKSTRUCT).vkCode, Keys))
            End Select
        End If
        Return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam)
    End Function

    Public Sub New()
        HHookID = SetWindowsHookEx(WH_KEYBOARD_LL, KBDLLHookProcDelegate, System.Runtime.InteropServices.Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32, 0)
        If HHookID = IntPtr.Zero Then
            Throw New Exception("Could not set keyboard hook")
        End If
    End Sub

    Protected Overrides Sub Finalize()
        If Not HHookID = IntPtr.Zero Then
            UnhookWindowsHookEx(HHookID)
        End If
        MyBase.Finalize()
    End Sub

End Class

Usage:
To create the hook

Private WithEvents kbHook As New KeyboardHook

Then each event can be handled:

Private Sub kbHook_KeyDown(ByVal Key As System.Windows.Forms.Keys) Handles kbHook.KeyDown Debug.WriteLine(Key.ToString) End Sub Private Sub kbHook_KeyUp(ByVal Key As System.Windows.Forms.Keys) Handles kbHook.KeyUp Debug.WriteLine(Key) End Sub

Note: To run this inside Visual Studio, you will need to go to:
Project -> [Project Name] Properties -> Debug -> Uncheck “Enable the Visual Studio hosting process”
As that intercepts the hooked messages before your program.

28
Mar
09

[VB.Net] Binary To String Conversion

    Public Function BinaryToString(ByVal Binary As String) As String
        Dim Characters As String = System.Text.RegularExpressions.Regex.Replace(Binary, "[^01]", "")
        Dim ByteArray((Characters.Length / 8 ) - 1) As Byte
        For Index As Integer = 0 To ByteArray.Length - 1
            ByteArray(Index) = Convert.ToByte(Characters.Substring(Index * 8, 8), 2)
        Next
        Return System.Text.ASCIIEncoding.ASCII.GetString(ByteArray)
    End Function

Usage:

Debug.WriteLine(BinaryToString("01110011 01101001 01101101 00110000 01101110"))

Would output:

sim0n

Debug.WriteLine(BinaryToString("01110011,01101001,01101101,00110000,01101110,"))

Would output:

sim0n