Launching another app from your own program - Windows Mobile Development and Hacking General

Hi there.
I'm learning how to write programs for my mobile, and at the moment, I'm working on an app which will generate a playlist for TCPMP and then launch TCPMP.
I've got right to the last bit, but now I can't find out how to execute the app.
I'm assuming that you do something like
system.shell("\path\to\app.exe")
But I can't find the system.shell (or equiv.) to run.
Can anyone point me in the right direction?
Thanks
Jon "The Nice Guy"

JonTheNiceGuy: with such a question, you really need to specify language, development environment (ideally) and target OSi.
I'm a c++ man, for which I'd createprocess or shellexecute.
V

Oops! Stupid of me. VB.net

In the Compact Framework system.diagnostics.process allows you to start an application and provide arguments for it

I've just tried to add the following code (each without success)
Dim process as system.diagnostics.process
Dim process as New System.Diagnostics.Process
Is this right? All I seem to have under system.diagnostics is stuff to do with tracing and debugging, not to start new processes, and I there doesn't seem to be any references I can add for it either...
Rgds,
Jon

I do not believe you can use System.Diagnostics.Process to run processes if you are using Compact Net Framework 1.x, (you can in the full net framework). Not sure about 2.x as I have not migrated yet.
try (this is C#)
[DllImport("coredll.Dll",EntryPoint="CreateProcess")]
private static extern int CreateProcess(string strImageName, string strCmdLine, IntPtr pProcessAttributes, IntPtr pThreadAttributes , int bInheritsHandle, int wCreationFlags, IntPtr pEnvironment, IntPtr pCurrentDir, Byte[] bArray, ProcessInfo oProc);
......
......
then
ProcessInfo pi = new ProcessInfo();
CreateProcess("myprogname", "-myprogargs", IntPtr.Zero, IntPtr.Zero, 0, 0, IntPtr.Zero, IntPtr.Zero, new Byte[128], pi)

So... here's my code so far (stripped out non-essential bits). Clicking on a button on the form triggers the sub doLaunchPlayer().
Code:
Imports System.Runtime.InteropServices
Public Class Starter
Dim strOutFile As String = "\stream.m3u"
Private Sub doLaunchPlayer()
SpawnProcess(strOutFile, "")
End Sub
Private Declare Function CreateProcess Lib "coredll.Dll" (ByVal strImageName As String, ByVal strCmdLine As String, ByVal pProcessAttributes As IntPtr, ByVal pThreadAttributes As IntPtr, ByVal bInheritsHandle As Integer, ByVal dwCreationFlags As Integer, ByVal pEnvironment As IntPtr, ByVal pCurrentDir As IntPtr, ByVal bArray() As [Byte], ByVal oProc As ProcessInfo) As Integer
Private Sub SpawnProcess(ByVal Application As String, ByVal Arguments As String)
Dim pi As New ProcessInfo
CreateProcess(Application, Arguments, IntPtr.Zero, IntPtr.Zero, 0, 0, IntPtr.Zero, IntPtr.Zero, New [Byte](128) {}, pi)
End Sub
End Class
Public Class ProcessInfo
Public Process As Integer
Public Thread As Integer
Public ProcessID As Integer
Public ThreadID As Integer
End Class
It's not running the associated application for a .m3u file. Changing to the following doesn't work either:
Code:
Private Sub doLaunchPlayer()
SpawnProcess("\Program Files\TCPMP\Player.exe", strOutFile)
End Sub
Any thoughts?

1) You should check the return code of CreateProcess.
2) Does VB need CreateProcess("\\Program Files\\TCMP\\...... ?
3) Try with a fullpath to Word or another integrated app, to check your code is correct.

I'd got the code wrong. Thanks for the pointer - I was looking in the wrong place for the exe!

Related

Using ShellExecuteEx using Visual Studio 2003 (C#/VB.NET)

Hi there,
OK, I took the hint about using shellexececuteex, but I can't find a code snippet which does the trick!
I found this link which gives some good code, but when I put it in my VB.NET app, it doesn't seem to like it.
At the line
Code:
DllImport("coredll") _
Private Shared Function ShellExecuteEx(ByVal ex As SHELLEXECUTEEX) As Integer
it says "Statement is not valid in namespace."
and
Code:
<DllImport("coredll")> _
Private Shared Function LocalAlloc(flags As Integer, size As Integer) As IntPtr()
says "Statement cannot appear within a method body. End of method assumed.
Can anyone point me in the right direction? Once I know what I'm doing (which may be a while!), I've got some funky stuff I want to do, but I need to figure out what I'm doing wrong first...
Thanks
Jon "The Nice Guy
Code:
Imports System.Runtime.InteropServices
Imports System.Text
Class SHELLEXECUTEEX
Public cbSize As Integer
Public fMask As Integer
Public hwnd As IntPtr
Public lpVerb As IntPtr
Public lpFile As IntPtr
Public lpParameters As IntPtr
Public lpDirectory As IntPtr
Public nShow As Integer
Public hInstApp As IntPtr
' Optional members
Public lpIDList As IntPtr
Public lpClass As IntPtr
Public hkeyClass As IntPtr
Public dwHotKey As UInt32
Public hIcon As IntPtr
Public hProcess As IntPtr
End Class 'SHELLEXECUTEEX
<DllImport("coredll")> _
Private Shared Function ShellExecuteEx(ByVal ex As SHELLEXECUTEEX) As Integer
<DllImport("coredll")> _
Private Shared Function LocalAlloc(flags As Integer, size As Integer) As IntPtr()
<DllImport("coredll")> Private Shared Sub LocalFree(ptr As IntPtr)
' Code starts here
Dim docname As String = "\windows\default.htm"
Dim nSize As Integer = docname.Length * 2 + 2
Dim pData As IntPtr = LocalAlloc(&H40, nSize)
Marshal.Copy(Encoding.Unicode.GetBytes(docname), 0, pData, nSize - 2)
Dim see As New SHELLEXECUTEEX
see.cbSize = 60
see.dwHotKey = 0
see.fMask = 0
see.hIcon = IntPtr.Zero
see.hInstApp = IntPtr.Zero
see.hProcess = IntPtr.Zero
see.lpClass = IntPtr.Zero
see.lpDirectory = IntPtr.Zero
see.lpIDList = IntPtr.Zero
see.lpParameters = IntPtr.Zero
see.lpVerb = IntPtr.Zero
see.nShow = 0
see.lpFile = pData
ShellExecuteEx(see)
LocalFree(pData)
If you want to start an executable, take a look at the following example which uses createprocess in VB using API
http://samples.gotdotnet.com/quickstart/CompactFramework/doc/waitforsingleobject.aspx
And some other interesting information using ShellExecute and Process.Start
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=404967&SiteID=1
Eelco
I need to execute a m3u file, or (in another case) a cab file.
I can't help you with the .NET stuff, but if you are trying to install cabs programatically you should read up on wceload.exe and it's parameters.
Unfortunately this will still require the use of CreateProcess (something that is very easy in native code, but apparently not so in .NET) but you will have control over several things like messages asking were to install and progress bar being shown.
http://msdn.microsoft.com/library/d...n-us/wcepbguide5/html/wce50lrfWceloadTool.asp
Bump
Just to let you all know, I got around needing the .cab file thang by installing the MrClean AUK2 ROM. I still want to be able to launch files with any extension though.
Jon
Use the registry to find out what program should launch for that extension and then launch that program with the file name as a parameter.
Which is what I was after in this thread where people told me to use ShellExecuteEX! LOL
If you can tell me how to get the application handler from the registry based on a file extension, then I'll write it into my app, otherwise, I'll need to use the ShellExecuteEX to launch the file, and let Windows handle the extension.

Problem access RIL.DLL - VB.NET CF 1.x

Hi,
i try to access ril functions from VB.NET
but get an NotSupportetException if i call RIL_Initialize.
Need help please:
Code:
Private Shared hRil As Long = 0
Public Delegate Function dRilResultCallback(ByVal dwCode As Long, ByVal hrCmdID As Int32, ByVal lpData As Byte(), ByVal cdData As Long, ByVal dwParam As Long) As Long
Public Delegate Function dRilNotifyCallback(ByVal dwCode As Long, ByVal lpData() As Byte, ByVal cdData As LocalDataStoreSlot, ByVal dwParam As Long) As Long
<DllImport("Ril.dll")> _
Private Shared Function RIL_Initialize( _
ByVal Index As Int32, _
ByVal pResult As dRilResultCallback, _
ByVal pNotify As dRilNotifyCallback, _
ByVal NotifyClass As Byte, _
ByVal Params As Byte, _
ByRef hResult As Long _
) As Long
End Function
Private Shared Function RilResultCallback(ByVal dwCode As Long, ByVal hrCmdID As Int32, ByVal lpData As Byte(), ByVal cdData As Long, ByVal dwParam As Long) As Long
End Function
Private Shared Function RilNotifyCallback(ByVal dwCode As Long, ByVal lpData() As Byte, ByVal cdData As LocalDataStoreSlot, ByVal dwParam As Long) As Long
End Function
Public Shared Function InitRil() As Boolean
Dim nRetVal As Long = 0
If (hRil = 0) Then
Try
Dim cbResult As dRilResultCallback = AddressOf RilResultCallback
Dim cbNotify As dRilNotifyCallback = AddressOf RilNotifyCallback
nRetVal = RIL_Initialize(1, cbResult, cbNotify, 0, 0, hRil)
Catch ex As Exception
MsgBox("Execption: " & ex.Message, MsgBoxStyle.Critical)
End Try
End If
i have found 1000 samples in C++ but i to really hard to translate it in VB.
I am not familiar with VB.NET, but few suggestions:
1. If you debug the program with emulator, make sure you choose the EMU image with virtual RIL support.
2. If you debug the prog with WM5 device, make sure you have priviledge signed your prog.
3. In C++, I use &g_hRil instead of g_hRil in the last para of Ril_Initial function, any idea?
4. Pay more attention to the CALLBACK functions, Result callback and Notify callback.
ahe said:
2. If you debug the prog with WM5 device, make sure you have priviledge signed your prog.
Click to expand...
Click to collapse
I test this way. Perhaps if i use certificates it works.
Then simply signed it with WM5 SDK test priviledged cert.
Ok, my certification is installed and isgned the app.
But same error.
It looks like an error in declaraion....
BongoUser said:
Ok, my certification is installed and isgned the app.
But same error.
It looks like an error in declaraion....
Click to expand...
Click to collapse
The RIL declarations are not correct
Code:
[FONT=Verdana, Arial, Helvetica][SIZE=2][COLOR=#333333]typedef void (CALLBACK *RILRESULTCALLBACK)(
DWORD dwCode, // @parm result code
HRESULT hrCmdID, // @parm ID returned by the command that originated this response
const void* lpData, // @parm data associated with the notification
DWORD cbData, // @parm size of the strcuture pointed to lpData
DWORD dwParam // @parm parameter passed to <f RIL_Initialize>
);
typedef void (CALLBACK *RILNOTIFYCALLBACK)(
DWORD dwCode, // @parm notification code
const void* lpData, // @parm data associated with the notification
DWORD cbData, // @parm size of the strcuture pointed to lpData
DWORD dwParam // @parm parameter passed to <f RIL_Initialize>
);
[/COLOR][/SIZE][/FONT]
[FONT=Verdana, Arial, Helvetica]
[/FONT] lpData is long in the C declaration, then try to cast it later, not in the declaration directly.
[FONT=Verdana, Arial, Helvetica]Change your Byte() in the callback to IntPtr. And use Marshal.PtrToStruct to put it in one of the RIL structs to get the data.[/FONT]
Then in order to simplify your job, why don't you write a library in C/C++ that you call in your VB.net appl. in place of trying to port the code directly and reinvent the wheel.
ps.: as I said .NET is crap, just use a real programming language.
Cheers,
.Fred

Server Application problem

Using vb.net i have created an application which listens on TCP port 85 for incoming connections via telnet, reads a line of text (until ascii 13) and then parses that line (phone number, ascii 9, sms message, ascii 13) and sends it as an sms....
I have two small problems:
1: i am unable to work out if the sms was sent ok or not, i do not know how to get the return code from the send sms function into a useable format...
2: all this works fine (apart from the above) it parses the line, and sends the sms (i know it sends as it delivers to my other phone, but i need to have it print the result to the socket) but ONLY over the USB connection on 169.254.x.x, and not if i change the listening IP to 192.168.0.12 (this is a static ip the device is always assigned by my dhcp server) i cannot connect to the server. I would like to use this wirelessly as that way i can forward the port using my router and therefore access the sms on the phone from an external server without needing my laptop to be switched on!
I have included my code below... excuse the sloppiness, i only started using vb.net today, but any help in trying to acheive what i am attempting would be much appreciated!
Code:
Imports System.Runtime.InteropServices
Imports interopserv = System.Runtime.InteropServices
Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports Microsoft.VisualBasic
Public Enum SMS_ADDRESS_TYPE
SMSAT_UNKNOWN = 0
SMSAT_INTERNATIONAL
SMSAT_NATIONAL
SMSAT_NETWORKSPECIFIC
SMSAT_SUBSCRIBER
SMSAT_ALPHANUMERIC
SMSAT_ABBREVIATED
End Enum 'SMS_ADDRESS_TYPE
Public Structure PhoneAddress
'/ <summary>The address type.</summary>
Public AddressType As SMS_ADDRESS_TYPE
'/ <summary>The phone number in string format.</summary>
Public Address() As Char
End Structure 'PhoneAddress
Public Class SMS
Private Shared SMS_MSGTYPE_TEXT As String = "Microsoft Text SMS Protocol"
Private Shared SMS_MODE_SEND As Long = &H2
Private Shared SMS_OPTION_DELIVERY_NONE As Long = &H0
Private Shared SMS_OPTION_DELIVERY_NO_RETRY As Long = &H1
Private Shared PS_MESSAGE_OPTION_NONE As Long = &H0
Public Shared Function StrToByteArray(ByVal str As String) As Byte()
Dim encoding As New System.Text.ASCIIEncoding()
Return encoding.GetBytes(str)
End Function 'StrToByteArray
Private Enum SMS_DATA_ENCODING
SMSDE_OPTIMAL = 0
SMSDE_GSM
SMSDE_UCS2
End Enum 'SMS_DATA_ENCODING
Public Enum PROVIDER_SPECIFIC_MESSAGE_CLASS
PS_MESSAGE_CLASS0 = 0
PS_MESSAGE_CLASS1
PS_MESSAGE_CLASS2
PS_MESSAGE_CLASS3
End Enum 'PROVIDER_SPECIFIC_MESSAGE_CLASS
Private Enum PROVIDER_SPECIFIC_REPLACE_OPTION
PSRO_NONE = 0
PSRO_REPLACE_TYPE1
PSRO_REPLACE_TYPE2
PSRO_REPLACE_TYPE3
PSRO_REPLACE_TYPE4
PSRO_REPLACE_TYPE5
PSRO_REPLACE_TYPE6
PSRO_REPLACE_TYPE7
PSRO_RETURN_CALL
PSRO_DEPERSONALIZATION
End Enum 'PROVIDER_SPECIFIC_REPLACE_OPTION
Private Structure TEXT_PROVIDER_SPECIFIC_DATA
Public dwMessageOptions As Long
Public psMessageClass As PROVIDER_SPECIFIC_MESSAGE_CLASS
Public psReplaceOption As PROVIDER_SPECIFIC_REPLACE_OPTION
End Structure 'TEXT_PROVIDER_SPECIFIC_DATA
<System.Runtime.InteropServices.DllImport("sms.dll")> _
Private Shared Function SmsOpen(ByVal ptsMessageProtocol As [String], _
ByVal dwMessageModes As Int32, _
ByRef psmshHandle As IntPtr, _
ByVal phMessageAvailableEvent As IntPtr) As IntPtr
End Function
<System.Runtime.InteropServices.DllImport("sms.dll")> _
Private Shared Function SmsSendMessage(ByVal smshHandle As IntPtr, _
ByVal psmsaSMSCAddress As Int32, _
ByVal psmsaDestinationAddress As IntPtr, _
ByVal pstValidityPeriod As Int32, _
ByVal pbData As IntPtr, _
ByVal dwDataSize As Int32, _
ByVal pbProviderSpecificData() As Byte, _
ByVal dwProviderSpecificDataSize As Int32, _
ByVal smsdeDataEncoding As Int32, _
ByVal dwOptions As Int32, _
ByVal psmsmidMessageID As Int32) As IntPtr
End Function
<System.Runtime.InteropServices.DllImport("sms.dll")> _
Private Shared Function SmsClose(ByVal smshHandle As IntPtr) As IntPtr
End Function
<StructLayout(LayoutKind.Sequential)> _
Public Structure MsgSize
Public MsgSz As Int32
End Structure
<StructLayout(LayoutKind.Sequential)> _
Public Structure ProviderDataSize
Public ProvDataSize As Int32
End Structure
Public Shared Function SendMessage(ByVal sPhoneNumber As String, ByVal sMessage As String) As Integer
Dim retVal As IntPtr = IntPtr.Zero
Dim smsHandle As IntPtr = IntPtr.Zero
Dim smsProviderData As IntPtr = IntPtr.Zero
Dim smsMessage As IntPtr = IntPtr.Zero
Dim msgresult As Int32
Dim ProvData(12) As Byte
Try
retVal = SmsOpen(SMS_MSGTYPE_TEXT, SMS_MODE_SEND, smsHandle, IntPtr.Zero)
If retVal.ToInt32 <> 0 Then
Throw New Exception("Could not open SMS.")
End If
'Set address structure
Dim smsatAddressType As Byte() = BitConverter.GetBytes(SMS_ADDRESS_TYPE.SMSAT_UNKNOWN)
Dim ptsAddress As Byte() = System.Text.Encoding.Unicode.GetBytes(sPhoneNumber)
Dim smsAddressTag(smsatAddressType.Length + ptsAddress.Length) As Byte
Array.Copy(smsatAddressType, 0, smsAddressTag, 0, smsatAddressType.Length)
Array.Copy(ptsAddress, 0, smsAddressTag, smsatAddressType.Length, ptsAddress.Length)
Dim smsAddress As IntPtr = Marshal.AllocHLocal(smsAddressTag.Length)
System.Runtime.InteropServices.Marshal.Copy(smsAddressTag, 0, smsAddress, smsAddressTag.Length)
'Set message
Dim smsMessageTag As Byte() = System.Text.Encoding.Unicode.GetBytes(sMessage)
smsMessage = Marshal.AllocHLocal(smsMessageTag.Length)
System.Runtime.InteropServices.Marshal.Copy(smsMessageTag, 0, smsMessage, smsMessageTag.Length)
retVal = SmsSendMessage(smsHandle, 0, smsAddress, 0, smsMessage, smsMessageTag.Length, _
ProvData, 12, SMS_DATA_ENCODING.SMSDE_OPTIMAL, SMS_OPTION_DELIVERY_NONE, 0)
msgresult = retVal.ToInt32
'Stream.Write(StrToByteArray(retVal), 0, retVal.Length)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Try
retVal = SmsClose(smsHandle)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return msgresult
End Function
End Class 'SMS
Public Class MyTcpListener
Public Shared Function StrToByteArray(ByVal str As String) As Byte()
Dim encoding As New System.Text.ASCIIEncoding()
Return encoding.GetBytes(str)
End Function 'StrToByteArray
Public Shared Sub Main()
Dim server As TcpListener
server = Nothing
Try
' Set the TcpListener on port 13000.
Dim port As Int32 = 85
Dim localAddr As IPAddress = IPAddress.Parse("0.0.0.0")
server = New TcpListener(localAddr, port)
' Start listening for client requests.
server.Start()
' Buffer for reading data
Dim bytes(1024) As Byte
Dim data As String = Nothing
' Enter the listening loop.
While True
Console.Write("Waiting for a connection... ")
' Perform a blocking call to accept requests.
' You could also user server.AcceptSocket() here.
Dim client As TcpClient = server.AcceptTcpClient()
Console.WriteLine("Connected!")
data = Nothing
' Get a stream object for reading and writing
Dim stream As NetworkStream = client.GetStream()
Dim i As Integer
Dim c As Char
Dim smeg As Char
Dim values(4) As String
'Dim msg As String
Dim j As String
i = stream.ReadByte()
While (i <> 1)
c = Microsoft.VisualBasic.ChrW(i)
data = data & c
i = stream.ReadByte()
End While
Dim mSep As String
mSep = "---------"
smeg = Microsoft.VisualBasic.ChrW(9)
values = data.Split(smeg)
stream.Write(StrToByteArray(values(0)), 0, values(0).Length)
stream.Write(StrToByteArray(mSep), 0, mSep.Length)
stream.Write(StrToByteArray(values(1)), 0, values(1).Length)
Dim result As Int32
result = SMS.SendMessage(values(0), values(1))
stream.Write(StrToByteArray(Microsoft.VisualBasic.ChrW(result)), 0, 1)
' Shutdown and end connection
client.Close()
stream.Close()
End While
Catch e As SocketException
Console.WriteLine("SocketException: {0}", e)
Finally
server.Stop()
End Try
Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")
'Console.Read()
End Sub 'Main
End Class 'MyTcpListener

Visual Basic developpement Help

Hi
i try to developp pocket pc application in visual basic netcf3.5
i wan't this application start minimized but i have an error
the code:
Code:
Public Class Formmain
Private Sub Formmain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.WindowState = FormWindowState.Minimized
End Sub
End Class
visual studio 2008 return this error:
Code:
'Minimized' is not a member of 'System.Windows.Forms.FormWindowState'.
it seem FormWindowState don't have minimized option only normal & maximize
if someone have an idea
thank a lot
Use:
ShowWindow(this.Handle, SW_MINIMIZED);
Declare:
[DllImport("coredll.dll")]
static extern int ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_MINIMIZED = 6;
hujer said:
Use:
ShowWindow(this.Handle, SW_MINIMIZED);
Declare:
[DllImport("coredll.dll")]
static extern int ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_MINIMIZED = 6;
Click to expand...
Click to collapse
In VB.NET it would be:
'Declare:
Private Const SW_MINIMIZED As Integer = 6
Private Declare Function ShowWindow Lib "coredll.dll" (ByVal hWnd As IntPtr, ByVal nCmdShow As Integer) As Integer
'Call this in the form_load event:
ShowWindow(Me.Handle, SW_MINIMIZED)
GeirFrimann said:
In VB.NET it would be:
'Declare:
Private Const SW_MINIMIZED As Integer = 6
Private Declare Function ShowWindow Lib "coredll.dll" (ByVal hWnd As IntPtr, ByVal nCmdShow As Integer) As Integer
'Call this in the form_load event:
ShowWindow(Me.Handle, SW_MINIMIZED)
Click to expand...
Click to collapse
won't work but possible i have an error in my code i'm newbie in dev
i try like this
Code:
Public Class Formmain
Private Const SW_MINIMIZED As Integer = 6
Private Declare Function ShowWindow Lib "coredll.dll" (ByVal hWnd As IntPtr, ByVal nCmdShow As Integer) As Integer
Private Sub Formmain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ShowWindow(Me.Handle, SW_MINIMIZED)
End Sub
End Class
if you can help me that would be wonderfull
thanks
Read the MSDN library about minimising/closing .net cf forms. The MSDN library shows you a little image of a device for methods/properties etc that are supported, minimize is not.
Be aware though that form's by default are minimised and not closed when pressing the X in the corner. I've never tried this nor recommend it but see what happens when you call form.close() method in the load, it may minimse the form or it may crap out all together. What are your reasons for doing this?
Take it from someone who develops on these devices for a living.., programming the .net compact framework can be a very frustrating effort at times. You work with a much lower subset of functionality than in the full framework, you have to take caution to how much memory you use, some things don't work the same way as they do on the full framework and the most recent discovery I've had is that the same framework on different os's can have very different behaviour, i.e. control events firing when hiding them.
Good luck

Developer API Tricks in VB.Net 2008

Here are a few useful tricks using p/invoke that some developers may find usefull and some were hard to find on the net so I created my own Wrappers with a little research.
The following code is a Helper Class to apply the WM6.5 visual styles to some controls using .net framework. This Wrapper lets you apply the visual style to the Tab Control, Apply Background Image to ListView, Enable Double Buffering for ListView, Show Grid Lines in ListView and Enable Visual Style for ListView. To call these functions you just simply put the control in the brackets you wish to apply the visual style to. For Example: EnableListViewStyle(lvMyListview)
Code:
Public Class VisualStyleHelper
Public Const GWL_STYLE As Integer = -16
Public Const GW_CHILD As Int32 = 5
Public Const LVS_EX_THEME As Integer = &H2000000
Public Const LVM_SETEXTENDEDLISTVIEWSTYLE As Integer = &H1000 + 54
Public Const LVM_GETEXTENDEDLISTVIEWSTYLE As Integer = &H1000 + 55
Public Const LVS_EX_GRIDLINES As Integer = &H1
Public Const LVS_EX_DOUBLEBUFFER As Integer = &H10000
Public Const LVBKIF_SOURCE_HBITMAP As Integer = &H1
Public Const LVM_SETBKIMAGE As Integer = (&H1000 + 138)
Private Declare Function SendMessage Lib "coredll" (ByVal hWnd As IntPtr, ByVal Msg As UInt32, ByVal wParam As UInt32, ByVal lParam As Integer) As IntPtr
Private Declare Function SendMessage Lib "coredll" (ByVal hWnd As IntPtr, ByVal Msg As UInt32, ByVal wParam As UInt32, ByRef img As LVBKIMAGE) As IntPtr
Public Structure LVBKIMAGE
Public ulFlags As Integer
Public hbm As IntPtr
Public pszImage As IntPtr
Public cchImageMax As Integer
Public xOffsetPercent As Integer
Public yOffsetPercent As Integer
End Structure
'Tab Control Helper
Public Shared Sub EnableTabStyle(ByVal tabControl As TabControl)
Dim hNativeTab As IntPtr = WindowHelper.GetWindow(tabControl.Handle, GW_CHILD)
Dim Style As Integer = WindowHelper.GetWindowLong(hNativeTab, GWL_STYLE)
Style = WindowHelper.SetWindowLong(hNativeTab, GWL_STYLE, Style Or &H4000)
End Sub
'ListView Control Helper
Public Shared Sub EnableListViewStyle(ByVal listView As ListView)
Dim currentStyle As Integer = SendMessage(listView.Handle, CUInt(LVM_GETEXTENDEDLISTVIEWSTYLE), 0, 0)
SendMessage(listView.Handle, CUInt(LVM_SETEXTENDEDLISTVIEWSTYLE), 0, currentStyle Or LVS_EX_THEME)
End Sub
'Set Background Image to ListView
Public Shared Sub SetBackgroundImage(ByVal listView As ListView, ByVal path As String)
Dim bitmap As New Bitmap(path)
Dim hBitmap As IntPtr = bitmap.GetHbitmap()
bitmap.Dispose()
Dim lvImage As New LVBKIMAGE()
lvImage.hbm = hBitmap
lvImage.ulFlags = LVBKIF_SOURCE_HBITMAP
SendMessage(listView.Handle, LVM_SETBKIMAGE, 0, lvImage)
End Sub
'Display GridLines in ListView
Public Shared Sub ShowGridLines(ByVal listView As ListView)
Dim currentStyle As Integer = SendMessage(listView.Handle, CUInt(LVM_GETEXTENDEDLISTVIEWSTYLE), 0, 0)
SendMessage(listView.Handle, CUInt(LVM_SETEXTENDEDLISTVIEWSTYLE), 0, currentStyle Or LVS_EX_GRIDLINES)
End Sub
'Reduces Flicker in ListView
Public Shared Sub EnableDoubleBuffering(ByVal listView As ListView)
Dim currentStyle As Integer = SendMessage(listView.Handle, CUInt(LVM_GETEXTENDEDLISTVIEWSTYLE), 0, 0)
SendMessage(listView.Handle, CUInt(LVM_SETEXTENDEDLISTVIEWSTYLE), 0, currentStyle Or LVS_EX_DOUBLEBUFFER)
End Sub
End Class
Here is a simple function to return the given bytes in Megabytes as a string:
Code:
Public Shared Function CBytesToMBytes(ByVal Bytes As Double) As String
Dim dblAns As Double
dblAns = (Bytes / 1024) / 1024
Return Format(dblAns, "###,###,##0.00 MB")
End Function
Here is a Class Wrapper I created which lets you use various methods to Soft Reset and even use HTCUtil.dll to Hard Reset your device:
Code:
Public Class DeviceBootHelperClass
Const EWX_REBOOT = 2
<DllImport("HtcUtil")> _
Public Shared Sub HTCUtilTurnOnFlightMode()
End Sub
<DllImport("HtcUtil")> _
Public Shared Sub HTCUtilSetClearStorageFlag()
End Sub
<DllImport("HtcUtil")> _
Public Shared Sub HTCUtilPowerOffReset()
End Sub
<DllImport("HtcUtil")> _
Public Shared Sub HTCUtilDeviceOff()
End Sub
<DllImport("HtcUtil")> _
Public Shared Sub HTCUtilEnterBootloaderMode()
End Sub
<DllImport("aygshell")> _
Private Shared Function ExitWindowsEx(ByVal dwFlags As Integer, ByVal dwReserved As Integer) As Boolean
End Function
<DllImport("coredll")> _
Private Shared Function KernelIoControl(ByVal dwIoControlCode As Integer, _
ByVal lpInBuf As IntPtr, ByVal nInBufSize As Integer, ByVal lpOutBuf As IntPtr, _
ByVal nOutBufSize As Integer, ByRef lpBytesReturned As Integer) As Integer
End Function
Public Shared Sub KernelIOControlSoftResetMethod()
Const IOCTL_HAL_REBOOT As Integer = &H101003C
Dim bytesReturned As Integer = 0
KernelIoControl(IOCTL_HAL_REBOOT, IntPtr.Zero, 0, IntPtr.Zero, 0, bytesReturned)
End Sub
Public Shared Sub HTCUtilSoftResetMethod()
Try
HTCUtilPowerOffReset()
Catch ex As Exception
End Try
End Sub
Public Shared Sub HTCUtilPowerOffMethod()
Try
HTCUtilDeviceOff()
Catch ex As Exception
End Try
End Sub
Public Shared Sub HTCUtilHardResetMethod()
Try
HTCUtilTurnOnFlightMode()
HTCUtilSetClearStorageFlag()
HTCUtilPowerOffReset()
End If
Catch ex As Exception
End Try
End Sub
Public Shared Sub ExitWindowsExSoftResetMethod()
Try
ExitWindowsEx(EWX_REBOOT, 0)
Catch ex As Exception
End Try
End Sub
Public Shared Sub EnterBootloaderMode()
Try
HTCUtilEnterBootloaderMode()
Catch ex As Exception
End Try
End Sub
End Class
If you like my work, then please feel free to buy me a beer!
Thanks, this will be very useful
orb3000 said:
Thanks, this will be very useful
Click to expand...
Click to collapse
Hi, I have also wrote my own Window API wrapper which allows for enabling and disabling windows, getting the full exe file path from a given window class, a simple class for restarting an application and more will be uploaded soon. All this is used in my Touch Tools 2.0 Suite!
Great to know!, looking forward for your release
Can you add
wifi on/off/toggle
bluetooth on/off/toggle
gprs on/off/toggle
VisualStyleHelper needs WindowHelper class, which is not included. Google search for WindowHelper shows C# class only, no VB code.
Here it is:
Code:
Public Class WindowHelper
Private Const GW_HWNDFIRST As UInteger = 0
Private Const GW_HWNDLAST As UInteger = 1
Private Const GW_HWNDNEXT As UInteger = 2
Private Const GW_HWNDPREV As UInteger = 3
Private Const GW_OWNER As UInteger = 4
Private Const GW_CHILD As UInteger = 5
<DllImport("coredll.dll")> _
Public Shared Function GetWindow(ByVal hWnd As IntPtr, ByVal uCmd As UInteger) As IntPtr
End Function
<DllImport("coredll.dll", SetLastError:=True)> _
Public Shared Function GetWindowText(ByVal hWnd As IntPtr, <Out()> ByVal lpString As StringBuilder, ByVal nMaxCount As Integer) As Integer
End Function
<DllImport("coredll.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Public Shared Function GetWindowTextLength(ByVal hWnd As IntPtr) As Integer
End Function
<DllImport("coredll.dll")> _
Public Shared Function GetParent(ByVal hWnd As IntPtr) As IntPtr
End Function
<DllImport("coredll.dll")> _
Public Shared Function GetWindowLong(ByVal hWnd As IntPtr, ByVal cmd As Integer) As Integer
End Function
<DllImport("coredll.dll")> _
Public Shared Function GetActiveWindow() As IntPtr
End Function
<DllImport("coredll.dll")> _
Public Shared Function SetWindowLong(ByVal hWnd As IntPtr, ByVal nIndex As Integer, ByVal newWndProc As IntPtr) As Integer
End Function
End Class
@Corias
Lol, how could I have missed including the Window Helper Class! I will prepare some files and include all my classes in them so it will give everyone better understanding.
BR
Gaz
Good. I tried to convert VC# Window helper, everything works except EnumChildWindows (VB reports missing type Window). Any ideas on it?
Awesome work, will try it when i finish the main skeleton of my little program. Will post soon.
... and thank you

Categories

Resources