Category Archives: Api/Operating System

Code and posts related to the windows api and operating system.

Getting the Computers Windows Directory using VB and Visual Basic.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 3.67 out of 5)
 

This little article will show you how to get the Windows directory/folder using both classic vb and vb.net. For some reason Microsoft didn’t add built-in support for getting the path of the users windows directory until .NET 4.0. It is located under the: Environment.SpecialFolders feature. Otherwise I will show a way to get the windows path in the earlier versions of VB.NET and a way to get the directory path using VB 6.0 and Visual Basic.NET.


Both VB6.0 and Visual Basic NET

This is a simple API call that will give you the windows installed directory for the computer. You just need to create a string buffer and the api function will set the information you want in that buffer.

'Visual Basic 6.0 Declare

  Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long
'Visual Basic.NET Declare

 Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Int32) As Int32

Remaining code for API Method for All VB’s below…

'For both VB and VB.NET. This variable is for receiving the path from the API call.

    Dim winDir As String

 'Create a simple string buffer that will be passed to the api call to receive the directory for windows.

     winDir = Space$(255)

  'The winDir variable will get the value from the api call.

      GetWindowsDirectory winDir, Len(winDir)

'Trim the end of the value to remove the unused whitespaces from the string buffer.

      winDir = RTrim(winDir)

'This should throw a message box displaying the windows directory for the target computer.

    MsgBox(winDir)

When executing the code above, you should get a messagebox with the target computers Windows directory. It could be something similar to: “C:\Windows”


.NET based only using MY. below

Like I mentioned earlier Microsoft failed to include the Windows Directory as a Special Folder until .NET 4.0. But there is a another easy way to do it if you don’t want to use the API method.

This first way will actually use the Special Folder feature in .NET but will target the Environment.SystemDirectory. Since the System32 directory is always located under the base windows folder all you have to do is get the parent path of the SystemDirectory.

 MsgBox(My.Computer.FileSystem.GetParentPath(Environment.SystemDirectory))

The code above will throw a message with the parent path for the System32 directory. In my case is returned ‘c:\Windows’ just like the API version did.


There are other ways to get the windows direcory like checking a environment variable that I might add later on. The API version works great for both VB 6.0 and VB.NET, and the System32 method works just fine for .NET.  Remember Microsoft included the WindowsDirectory as a SpecialFolder in Visual Basic 2010 so you should use that method if possible. Anyways, thats all!

         Jason

Revised: 2015

Check if Windows or your Program is in 64-bit or 32-bit Mode using VB.NET and Higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 4.00 out of 5)
 

A while back I made a simple post on using WMI (Windows Management Instrumentaion) to check if the operating system your program was running on was 32-bit or 64-bit. The main problem with that method is its not supported on Windows XP and doesn’t tell you what mode your application is running in. I made a small example with different methods that should be near fool proof. I have 4 methods of checking if your application is 32 bit (x86) or 64 bit (x64 or AMD64 which is the code name). I also have 5 methods of checking what mode the operating system is running in. If you still can’t pin down whether your application/operating system is 32 or 64 bit then I don’t know what to tell you. BTW here is a link to the earlier post I made on how to easily check if the operating system is 32-bit or 64-bit using WMI, which applications running on Vista or Windows 7 can use just fine.

Image of example application

There is to much code in the example I made to post here. You should definitely download it and check it out. It was made with VB 2005 but the codes will work in VB.NET 2002,.NET 2003, Visual Basic 2008, and Visual Basic.NET 2010 as well. So I will just highlight a couple ways to determine your application and os mode.


The code below grabs a string from a registry key and examines the text. This  is pretty much a fool proof way of whether your cpu is running on a x86 or x64 operating system. All you need to do is check a specific key in the registry like below…

        Dim cpuID As String = _
            My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0", _
                "Identifier", "n/a")
        '
        'Get all chars from the beginning of the string until the first space is detected.
        cpuID = cpuID.Substring(0, cpuID.IndexOf(" "))

        MsgBox(cpuID)

If the key has x86 then its 32bit. If the key has AMD 64 or Intel64 then Windows is 64 bit. You can also check the registry key’s text to see if it contains AMD64 or Intel64. Of course if it contains x86 then the os is 32-bit and its 64-bit if it contains AMD64 or Intel64.

        'You can also check the registry string in this way.
        If LCase(cpuID).Contains("amd64") OrElse LCase(cpuID).Contains("intel64") Then

            MsgBox("It Is 64 Bit!")

        End If

I also want to show a simple way of checking if your application is running in 32 bit or 64 bit mode. You can simply check the size of IntPtr. If the pointer size is 4 bytes then its 32 bit. If its 8 bytes then its 64 Bit. This code simply checks if the size is higher than 4 or not. If its higher than 4 then its 64 bit. Otherwise its 32 bit. Remember, this method is the mode at the application level and not the platform level.

        'Basically if the Integer Pointer size is 4 then its 32 Bit and 8 is 64 Bit
        If IntPtr.Size > 4 Then

            MsgBox("64 Bit!")

        Else

            MsgBox("32 Bit!")

        End If

This post was mainly to give you an overview of a couple methods I used in the example program I made. The best thing would be for you to download the example and check out all of the methods I’ve come up with (or found out about).

I might add more to this little article in the future. That’s all for now. Have fun!

Jason

Target CPU and why you may get: “An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)”

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 4.83 out of 5)
 

An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

I remember getting quite annoyed a long time ago when I would get that error message above. Although it happened a few years ago I decided to write a brief post about it now anyways. You need to remember that this error message could possibly occur in different scenario’s and not just the way I got it.

I was trying to setup an example using VB 2005 that used a static.DLL file I made with C++. Whenever I would call a function from the DLL I would get the error message below…

‘BadImageFormatException was unhandled’

“An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)”

Picture of the Bad Format Error Message


It took some time and the advice of someone to find out why the problem kept popping up.

I use as my main computer an Intel Core2 based Processor/CPU which has 64 Bit support (x64 or AMD64, Intel64 is a clone of AMD64, which is the code name). Anyways, I use Windows Vista 64 Bit. That’s obviously not a problem in itself. I made the .DLL I mentioned above long before I upgraded to Vista 64. (BTW this error message will popup as well when running Windows7 64 Bit, and newer as well) The C++ .NET .DLL I made was based on Visual Studio.NET 2003 which will only compile 32 bit assemblies and was written when I still used Windows XP Professional 32 Bit (x86). Of course that’s not a problem in itself either. (Microsoft says .NET older than 2005 should Not be used for programming on any variant of Vista). The problem was when the two came together. I use Visual Studio 2005 Standard Edition which can target both 32 Bit and 64 Bit CPU’s and by default the profile is – Target CPU: AnyCPU. Since my CPU was running on a 64 bit Operating System, Visual Studio.NET would try to target using 64 Bit profiling instead of 32-Bit which the .DLL was written in. And that turned out to be the reason I kept getting that incorrect format error message. The program was targeting 64 Bit mode but the .DLL library I was using was 32 bit.


Picture of the Target CPU Compile Screen

To fix the problem all I had to do was change the: Target CPU: to ‘x86’ which is 32 Bit mode under the:

‘Project’ Menu: then under your project’s ‘Properties’: then under the ‘Compile’ Tab, and then ‘Advanced Compiler Settings’ which will have a small ComboBox near the bottom to select the ‘Target CPU’ to use, which I set to x86 in my case. But ‘x64′ is also available. In version 2010 of Visual Basic you can target Intel’s ‘Itanium’ processor as well..

I then re-ran the program and the calls to the .dll worked exactly like its supposed too. So if you ever get that Bad Format error message and your programming in 64 Bit mode you may try changing the Target CPU to x86 instead of the default AnyCPU (Or vice-versa).

Note: Visual Basic 2005/2008/2010 Express Edition IDE can also target a cpu architecture or platform but you change the settings in a different way using the configuration manager.

Jason

Revisited: 2015

How to Check if the Operating System is 32 Bit or 64 Bit using VB.NET, VB 2010, and Newer

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 4.00 out of 5)
 

I’ve seen many questions posted about how to check if the operating system the user is running is 64 Bit supported or just 32-Bit capable. 32 Bit is also referred to as x86 and 64-Bit is referred to as x64.

Update: October 19th 2010 – I decided to go ahead and add the simple code for checking OS Addressing to a new method if you use Visual Basic .NET 2010 and VB 2013.

Update 02/28/2011: I want to mention that I have another article for checking if the OS is 32bit/64bit, but also if your application is 32-bit/64-bit at this link here.


For Visual Basic.NET 2010 Only…

 Environment.Is64BitOperatingSystem

That property was added with the .NET Framework 4.0. Simply get the value from that property like below…

MsgBox(Environment.Is64BitOperatingSystem)

The property is a Boolean so it will return True if the Operating System is 64-Bit, otherwise it will return false.
If your not using VB 2010, 2013, and higher then continue reading the article…


Visual Basic.NET Older than version 2010

I’ve seen various options people have come up with like checking WOW64 emulation , ect… I’m not going to get into all of them. From what I understand those methods may not be 100%. So far in MY EXPERIENCE my version has been 100% when used with Vista and Windows 7. That is NOT to say that its perfect or has no flaws. Its just I have not had any problems, yet…

Anyways, its a very simple solution. Use the Windows built-in WMI (Windows Management Instrumentation) objects and features. Using WMI is quite easy with .NET. I unfortunately won’t be providing VB 5 or Visual Basic 6.0 source code. But the basics are still the same. I think VB classic can get support by referencing the WMI Scripting Library or using some API’s.

The apparent downside is that Microsoft says this wmi method is not supported on Windows XP. You can use environment variables and getnativesysteminfo api to query the os addressing. This wmi method so far appears to work just fine using Vista and Windows 7. 64 Bit operating systems became VERY popular with Vista, and especially Windows 7 due to ram being so cheap and if you wanted to address more than the 32 Bit limit of 4GB you needed to have an OS that can do 64 Bit addressing and a cpu capable of using AMD’s 64 Bit extensions. Intel CPU’s actually use AMD64 technology for their 64 Bit processors (Less Itanium)).

First of all in DotNET you want to add a Reference to two classes under: System.Managment. This will provide features to access wmi classes and features with minimal coding on your part. Of interest is the Management Class and the Management Object.

Below is the complete WMI based code that is used to get the Windows info…

    '
    'This function uses the WMI method to see if the operating system return 32-bit or 64-bit.
    Public Function getWMIInfo(ByVal wmiObjectInfo As String, ByVal wmiRelativePath As String) As String

        Try
            '
            'Give it something to report in case something wrong happens.
            getWMIInfo = "Nothing!" '

            Dim wmiClass As New System.Management.ManagementClass

            Dim wmiObject As New System.Management.ManagementObject

            wmiClass.Path.RelativePath = wmiRelativePath
            '
            'This will go through each item in the requested info. I only care about
            'the 1st for the most part but remeber that each instance could have different values.
            For Each wmiObject In wmiClass.GetInstances

                getWMIInfo = (wmiObject(wmiObjectInfo))
                '
                'I only want the first instance.

                Return getWMIInfo

            Next

        Catch exc As Exception

            Return exc.Message

        End Try

    End Function

Now all thats left to do is provide the object and path your interested in. The code below will throw a Messagebox with the message “32-bit” if your OS is x86 or “64-bit” if your OS is x64.

        '
        'Supply the WMI Object and Path to get whether the os is 32-bit or 64-bit.
        MsgBox(getWMIInfo("OSArchitecture", "Win32_OperatingSystem"))


That’s all there is to it! Like I said, so far its worked fine for me. Thats not to say there won’t be problems though. I will upload a new example I made at my vbcodesource.com website that shows how to get the Operating System and Applications addressing whethers its 32 Bit or 64 Bit that works with Windows XP, Vista, and Windows 7. Definitely, Let me know of any problems you run into using the source code in this article! Anyways have fun!

Jason

Revised: 2015

Free eBook: Patterns & Practices Application Architecture Guide 2.0

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (23 votes, average: 4.35 out of 5)
 

A while back Microsoft made available a new eBook for free called: Patterns and Pratices Application Architecture Guide 2.0

The download is about 3 megs of info and in the .pdf format. This book is should be very useful and helpful for .NET developers. Below are some of the features and Chapters in the free book.


Parts

Part I, Fundamentals
Part II, Design
Part III, Layers
Part IV, Archetypes

Foreword

  • Foreword by S. Somasegar
  • Foreword by Scott Guthrie

Chapters

  • Introduction
  • Architecture and Design Solutions At a Glance
  • Fast Track

 

Part I, Fundamentals

  • Chapter 1 – Fundamentals of Application Architecture
  • Chapter 2 – .NET Platform Overview
  • Chapter 3 – Architecture and Design Guidelines

   

Part II, Design

  • Chapter 4 – Designing Your Architecture
  • Chapter 5 – Deployment Patterns
  • Chapter 6 – Architectural Styles
  • Chapter 7 – Quality Attributes
  • Chapter 8 – Communication Guidelines

   

Part III, Layers

  • Chapter 9 – Layers and Tiers
  • Chapter 10 – Presentation Layer Guidelines
  • Chapter 11 – Business Layer Guidelines
  • Chapter 12 – Data Access Layer Guidelines
  • Chapter 13 – Service Layer Guidelines

   

Part IV, Archetypes

  • Chapter 14 – Application Archetypes
  • Chapter 15 – Web Applications
  • Chapter 16 – Rich Internet Applications (RIA)
  • Chapter 17 – Rich Client Applications
  • Chapter 18 – Services
  • Chapter 19 – Mobile Applications
  • Chapter 20 – Office Business Applications (OBA)
  • Chapter 21 – SharePoint Line-Of-Business (LOB) Applications

   

Appendix

  • Cheat Sheet – patterns & practices Pattern Catalog
  • Cheat Sheet – Presentation Technology Matrix
  • Cheat Sheet – Data Access Technology Matrix
  • Cheat Sheet – Workflow Technology Matrix
  • Cheat Sheet – Integration Technology Matrix

As you can see, this book can be very useful and helpful for those programming using the .NET framework. I recommend you download and check it out. Have fun!

Jason

More Microsoft “How Do I” Video Updates and Service Pack 1 for 2008

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (8 votes, average: 4.00 out of 5)
 

I just wanted to mention that Microsoft officially launched the RTM version Service Pack 1 for Visual Studio 2008 a couple weeks ago. It includes many fixes and some other features and improvements. WPF (Windows Presentation Foundation) performance has been greatly increased as well. Click Here to check out the Service Pack for VB 2008.

Also Microsoft has been adding new How Do I videos for Visual Basic 2008 the past couple of months it appears. Its definitely worth checking out. It looks like Microsoft added many newer videos working with Excel and Microsoft Office and services. Linq and data-based programming looks to be updated as well. Remember that MSDN has many 2005 based videos as well. Anyways, Click Here if you want to check out the full list of MSDN’s “How Do I” video series. Have Fun!

             Jason

Counters/Timers for the Visual Basic and VB.NET programmer

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 4.50 out of 5)
 

This article can be applied to all versions of VB including 6.0. Any code that may be posted here is originally set up for the .NET, but codes should be compatible with VB 6.0 by changing the variables and the declares to the right type and format. Example: If something is set to type Integer for .NET, the equivalent in VB 6.0 is Long. Otherwise, most of the .NET code should work fine in 6.0. The only trouble you may have is using 64 Bit Integers, which Classic VB doesn’t quite support. A work-around it using the Currency type (Which is technically a 64 Bit type) and converting it to a string while removing the decimal point. Check out this page for how to use the 64-bit Currency type in VB 6.0


Timers/Counters Info

This question on what timers are available using Visual Basic has a somewhat simple answer. Well, depending on the resolution you need to have.

GetTickCount – The “GetTickCount” function has a resolution of about 15-16(ms). IT returns the amount of milli-seconds that has elasped since your Windows OS has started.

    '
    'Provides about a 16(ms) resolution.
    '
    Private Declare Function getTickCount Lib "kernel32" Alias "GetTickCount" () As Integer

timeGetTime – If you need better accuracy, then you can try the multi-media timer: “timeGetTime” function, which can have a resolution of about 1(ms). It likewise returns the number of milli-seconds that has elasped since your Windows OS was started. But is has a much better resolution compared to the tick count function.

    '
    'Provides a resolution of 1(ms).
    '
    Private Declare Function timeGetTime Lib "winmm.dll" () As Integer

QueryPerformanceCounter – But, what if you need even better accuracy/resolution? The next option would be to use the computers high “Performance Timers”. (To check if the target computer actually supports this hardware timer, you would call either of the performance functions and look at its Return Value. If the return value is “0”(Zero), then the computer doesn’t support the hardware counter/timer feature. Not much more to say about this except you won’t be able to use this option.)

These functions are: ‘QueryPerformanceCounter’ and ‘QueryPerformanceFrequency’. With these functions its possible to get Sub-Millisecond accuracy/resolution. These timers could use a very small chip on your computers motherboard, which usually has a frequency of about: 3.6 Mhz. In some probably rare accurances these functions will actually use the RDTSC timestamp of your computers Processor. This would obviously have the highest resolution of all the timers in the computer. You can measure time in actual CPU Cycles. But i’ve rarely had this timer use that processor feature. In fact, I only witnessed it one time using my CPUs ReaDTimeStampCounter register. This would vary from computer to computer though. Microsoft says these functions could use either of these counters. * To determine which feature this counter/timer is using, you can use the function: QueryPerformanceFrequency function. This function returns the TickPerSeconds for the Performance Counter. Probably the most common value would be: 3579545. Which means that every second, this timer ticks 3,579,545 times, or around 3.6 million cycles per second. IF you have a 2ghz cpu/processor, and it is using your cpu’s rdtsc register, then the return value would be around the clockspeed of your processor.

    '
    'Gives you the current tick counts for the cpu since the computer has been running.
    'You could get very high resolutions in the Sub-Millisecond range with this counter/timer.
    Private Declare Function QueryPerformanceCounter Lib "kernel32" (ByRef counts As Long) As Integer
    '
    'Returns the frequency of the performanceCounter in counts-per-second.
    Private Declare Function QueryPerformanceFrequency Lib "kernel32" (ByRef frequency As Long) As Integer

RDTSC Register – This is a feature of all modern AMD/Intel CPUs/Processors since the original Pentium 1 was released. This timer ‘Ticks’ every time your Processor completes a ‘Cycle’. As you can probably discern, you can have some major high resolution timing available. But the big problem for getting to this timer if that its pretty much not possible to access this register on the CPU with the high level languages of Visual Basic and C#. But, if you can do a somewhat simple C++ DLL application, you can access this register and create a function in the .dll that will return the value of that timer when Visual Basic calls that .dll function. This is actually what I did with my: csRDTSC.dll I made with C++. IF you would like to use this .dll, just goto my main: http://www.vbcodesource.com webpage and under either the Classic or DotNET controls section page you can download and use it. The zip file includes the actual .DLL and a text file with the available functions.


Reference Information

Here is some reference links here that are related to these timer functions that would be more helpful.

QueryPerformanceCounter Reference…

Overview: QueryPerformanceCounter Function

How To: Time Managed Code Using QueryPerformanceCounter and QueryPerformanceFrequency


timeGetTime Reference

Multimedia Timer Reference – Overview of the timeGetTime related timers as msdn.com.
timeGetTime – The timeGetTime function retrieves the system time, in milliseconds. The system time is the time elapsed since Windows was started.


GetTickCount Reference…

GetTickCount Function

GetTickCount64 Function

How To – Retrieve Elapsed Time Since Windows Started


Conclusion

I really do hope you can get something useful from this small and brief article. I have many examples on my main webpage at: http://www.vbcodesource.com which shows how to use these timers. I even have a VB.NET – Example that compares the 3x most common timers that I outlined above. I also have a example for all of the Visual Basic versions (including Visual Basic.NET) that shows how to use my csRDTSC.DLL to get the time stamp value from the cpu and to calculate your processors clockspeed. Anyways, have fun 🙂

Jason

Minor Revision: 2015

Getting the Current Line Number in Textbox using VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
 

There is unfortunately no so-called ‘built-in’ way to get the current line number in a Visual Basic.NET Textbox control. Microsoft added that support in Visual Basic 2005/2008/2010. But many still use the original .NET versions which do not have that feature in the textbox control.

What to do? Well, there is a somewhat easy way to add this feature by using the Windows API. The API to use is the SendMessage API call. Below is the declaration, constant value, and line# variable…


Getting the Current Line Number code

    '
    'Unfortunately, .NET before 2005 doesn’t have a built-in feature to get the current
    'line. So I am using the SendMessage API to do it. You CAN do various extractions or
    'whatever to do it, but this is easier and more elegant in my opinion.
    '
    'Used to Send Messages to the control and will be used with a request for the
    'current line number in the textbox control.
    Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal winHandle As Int32, _
        ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32
    '
    'Constant found in the VB 6.0 API Viewer App IT will be passed to the SendMessage
    'API to tell the control to give the current Line # from the textbox character position.
    Public Const EM_LINEFROMCHAR = &HC9
    '
    'Will be used to contain the current line #.
    Dim lineNum As Int32

You can put the codes below in the textbox_Click, textbox_Keydown, textbox_TextChange event you want to take place or a button control  to get the line# results or whatever. In other words, put the code for where/when you want the current line results.

I put these codes in the Textbox_TextChanges event and used a label control to display the current line number. Its also worth nothing that Windows reports line # starting at “0”. So if the API returns a “0”, you can Add (+) one to the value which will then show the line# as 1. Another example is if the Windows API returns a 1, but in reality the current line is the second, then as before simple add (+) a One(1) to the value which will then be line #2.

        '
        'Call the API to get the Line # from the current char. Txt is your textbox control.
        lineNum = SendMessage(txt.Handle.ToInt32, EM_LINEFROMCHAR, -1, 0)
        '
        'Windows sees the first line in a edit box as line 0. So just add a value of 1 to the
        'result if you want the first line to be line #1.
        lblCurrent.Text = "Current Line: #" & (lineNum + 1).ToString
        '
        'Check for line count first to keep a possible error from happening if the textbox has
        'none.
        If txt.Lines.Length > 0 Then
            '
            'Get the text at the current line position.
            txtLineText.Text = txt.Lines.GetValue(lineNum)

        End If


Thats all there is to it! When you run your project and type your characters or make a new line or whatever in the textbox, the label control should show the number that the caret or cursor is currently at. If you want the Line # code to be updated when the mouse clicks on a different line or position, simply put the code above in the textbox_Click event. Have Fun!

Jason

Revisited: 2015

How to Set an Inputbox to Show Password Protected Characters using VB.NET and Higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 3.80 out of 5)
 

I made a previous article on password protecting an application and also using Inputboxes to get the username and password. A comment was left on how to make the Inputbox show password characters instead of the actual password being inserted. Well, that is what this article is for, to show how to use .NET and set the Inputbox (Modal Window) to display the input in its textbox as password based characters like asterisks or another char instead of the actual password. Its also called masking the characters in the inputbox. This article will mask the inputbox using Asterisks. But you can set whatever you want the characters to be.


NOTE: While the code in this article is for Visual Basic.NET, VB 2008, and VB.NET 2010, the same principals apply to classic VB as well. You want to Subclass, checking for WM_Create messages. When a WM_Create message is activated, you want to use the Findwindow API to determine whether the newly created window matches the title of the Inputbox you want to show. If it is use GetWindow to get the handle to the Child window which is the edit/text box. Then use the SendMessage API to tell the first ChildWindow in the Inputbox to display all input characters as password characters like asterisks.

Update note 02/27/2011: Steve mentioned that the API call FindWindow may not format correctly when you use Auto in declaring it. So you may have to change Auto to “Ansi” instead. For example: Private Declare Ansi Function FindWindow…..

Instead of Auto or Unicode. The alias name in the api call ends with an ‘A’ which denotes Ansi. If it ended with ‘W’ then it would be Unicode based.

If you run into that problem, use this Declare instead of the one later in the article.


    Private Declare Ansi Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Int32


AS outlined in a note above, the way I created a password only inputbox was to Subclass and monitor all the WM_Create messages being sent. When the application is notified that a new window was created, it will use the FindWindow API to check for the title of the newly created window. If the title of the window matches the title of the inputbox to be, it will return the handle to that window and call the GetWindow API function to get a handle to the first Child window, which with the Inputbox modal, is the Inputs Edit Box (Textbox) that you type the characters in. Once a handle to the Edit Box is taken, then a call to the SendMessage function to send a EM_SETPASSWORDCHAR message which will make the textbox display password characters which in this article tells the API to use Asterisks characters as the displayed password. You can make it display pretty much any character you want it to. That’s all I did!


    'If you used the Declare Ansi Function FindWindow version above, then ignore this one.
    'Will be used to get the window handles.
    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Int32

Now for some more api calls and variables.

    'Using it to get a handle to the child window of the inputbox.
    Private Declare Function GetWindow Lib "user32"? (ByVal hwnd As Int32, ByVal wCmd As Int32) As Int32

    'It tells the editbox (textbox) to display the contents/input as password characters.
    Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32

    'This will be the title of the Inputbox you will be throwing.
    'This is important since this is the key factor that the example looks for to identify the Inputbox.
    Dim inputTitle As String = "Enter the Password!"

    'Will hold the password returned by the inputbox message.
    Dim returnedPW As String

    'Will be used to code the password characters to appear as Asterisk characters.
    'You can actually have the password text display pretty much any character if you want too.
    'Just change the value of the const to the keycode character you want to use.
    Const asteriskKeyCode As Int32 = 42

    'Used by the SendMessage API to tell the inputbox editbox (textbox) to display the input as password characters.
    Public Const EM_SETPASSWORDCHAR As Int32 = &HCC

    'The message for when a new window is created.
    Public Const WM_CREATE As Int32 = &H1

    'Will hold the return value when calling the FindWindow function which will be the handle to the window.
    Dim windowHandle As Int32

    'Used to have the API call to look for a child based window.
    Public Const GW_CHILD As Int32 = 5

Now that the APIs and Variables are setup, its time for the rest of the codes.

This is the code I put in a button control.

    'This is a Button control I put some of the codes in…
    Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
        '
        'Simply display the inputbox with the title specified in the inputTitle variable and get the value that was put in the edit box.
        '
        'IMPORTANT: The Inputbox is required to have the same title as the window title passed to the FindWindow function. You can try using the Classname if you want to I guess.
        '
        'Clear the previous correct password even if one wasn’t selected.

        lblPw.Text = "InputBox Password:"

        returnedPW = InputBox("Enter the Password in the box!", inputTitle, "password!", 0)

        If Not returnedPW = Nothing AndAlso returnedPW = "password!" Then

            lblPw.Text = "InputBox Password is: " & returnedPW

        Else

            lblPw.Text = "InputBox Password is: Wrong!"

            MessageBox.Show("Wrong Password!", " Try Again")

        End If

    End Sub

This will set the password if the subclass method said their is a inputbox matching the one we want.

    Public Sub setPassword()

        'The codes below will setup the Inputbox Textbox (Edit Window) to be a password edit box and use the asterisk character as the display character.
        Dim editWindow As Int32

        'The Edit Window (Textbox) in the Inputbox is the first Child in the Inputbox Z Order. So just simply tell the API to get the handle to the first child window.
        editWindow = GetWindow(windowHandle, GW_CHILD)

        SendMessage(editWindow, EM_SETPASSWORDCHAR, asteriskKeyCode, 0)

    End Sub

Now for the subclass based procedure.

    '
    'This is used for the actual Subclassing to monitor for Created_Windows and will check to see if a Window matching the title of the inputbox we want.
    '
    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)

        'Have the base class handle all messages.
        MyBase.WndProc(m)

        'Check if a new window has been created.
        If m.Result.ToInt32 = WM_CREATE Then

            'Check the new window to see if it has the charateristics that we are looking for. Namely that is has the Title that we want to find.
            windowHandle = FindWindow(vbNullString, inputTitle)

            'Make sure that the WindowHandle is not 0 which should mean it have a handle to the Inputbox window that we are wanting.
        ElseIf windowHandle > 0 Then

            'Call the code to set the textbox to a password textbox.
            setPassword()

            'Reset the handle back to 0 since the window handle will be different each time you display Inputbox window.
            windowHandle = 0

        End If

    End Sub

That’s all! As is usually the case, with my articles, there is a example available that show how to do this. Simply head over to my http://www.vbcodesource.com/ site and look under the Visual Basic.NET – Examples. Anyways, have fun!

Jason

Revised: 2015

Auto Complete Support in Textbox and Combobox Controls using VB 6.0 and VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 2.00 out of 5)
 

Autocomplete is a very useful feature that Microsoft added with the release of Internet Explorer 5.0 and therefore Internet Explorer 5.0 or higher needs to be installed on the target computer. Adding autocomplete to your applications can be a real benefit to the user and is a easy feature to implement.

Note: Visual Basic 2005 and Visual Basic 2008 already has Autocomplete capabilities in the Textbox and Combobox controls by default.


There are a few different locations you can get the autocomplete data from…

  • File System
  • History List
  • URLs Recently Used
  • ALL URLs
  • ALL System Sources

There are likewise a few different options available to set the way you want AutoComplete to react.

  • Append
  • Suggest
  • Append & Suggest

Visual Basic.NET

    '
    'The API call that enables the autoComplete feature to your combo or textbox controls.
    Private Declare Sub SHAutoComplete Lib "shlwapi.dll" (ByVal controlHandle As Int32, ByVal _
        completeFlags As Int32)

Visual Basic 6.0

    '
    'The API call that enables the autoComplete feature to your combo or textbox controls.
    Private Declare Sub SHAutoComplete Lib "shlwapi.dll" (ByVal controlHandle As Long, ByVal _
        completeFlags As Long)

The SHAutoComplete API Sub is easy to use. The first parameter is the Handle to the Edit (Combobox/Textbox) control you want to enable Auto Complete too. The second Parameter is how you want your Autocomplete to react and display.


 

    '
    'Various Flags you can set to be the source.
    '
    Private Const Defaults = &H0

    Private Const Filesystem = &H1

    Private Const HistoryList = &H2

    Private Const URLRecentlyUsedList = &H4

    Private Const AllURLs = (HistoryList Or URLRecentlyUsedList)

    Private Const AllSystemsSources = AllURLs Or FileSystem

The flags below are used to specify how you want your autocomplete feature to react.

    '
    'Flags you can use to specify how your want autocomplete to react.
    '
    Private Const append = &H40000000 Or &H20000000

    Private Const suggest = &H10000000 Or &H80000000

    Private Const suggestAppend = &H40000000 Or &H10000000

Now that the API based codes are out of the way, you can setup the edit based controls (Like Textbox and Combobox) to have Autocomplete capabilities. Below is a simple example of adding autocomplete to a textbox control that I named txt.

        'Set autocomplete to the textbox using the system defaults.
        SHAutoComplete(txt.hWnd, Defaults)

        'You can also specify how it will react and what it will display.
        SHAutoComplete(txt.hWnd, suggest Or AllURLs)

If your using .NET, just change txt.hWnd to txt.Handle.ToInt32.

Unfortunately adding this feature to a Combobox isn’t as straight forward. Thats because when you use the Handle/Hwnd Property for the Combobox it returns the Main Window Portion of the control and NOT the Edit Window portion. There are a couple ways to get around this though. One way it to use the GetComboBoxInfo API or to use the FindWindowEx API call. I chose to go ahead and use the FindWindowEx API.


Visual Basic.NET

    '
    'API Function used to get the Edit window of a combobox control.
    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As  _
        Int32, ByVal hwndChildAfter As Int32, ByVal lpszClass As String, ByVal lpszWindow As String) As Int32

Visual Basic 6.0

    '
    'API Function used to get the Edit window of a combobox control.
    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal handle As _
        Long, ByVal hwndChildAfter As Long, ByVal lpszClass As String, ByVal lpszWindow As String) As Long

Now you just need to use the FindWindowEx Function using the 1st and 3rd parameter. And once you call the FindWindow function, simply pass its return value to the SHAutoComplete Method.

        '
        'Simply change this variable type to a Integer if your using VB.NET.
        Dim cmbHandle As Long

        'Retrieve the handle to the ‘Edit’ Window of the combobox. I named my Combobox control cmb.
        cmbHandle = FindWindowEx(cmb.hWnd, 0, "Edit", vbNullString)

        'Activate Autocomplete to the combobox edit window.
        SHAutoComplete(cmb.hWnd, Defaults)

Tip: Here is how you can specify exactly how to react and display….

        '
        'You can also specify how it will react and what it will display.
        SHAutoComplete(cmb.hWnd, suggest Or AllURLs)

Again, change cmb.hWnd to cmb.Handle.ToInt32 if your using Visual Basic.NET.

Thats all there is to it! Depending on your application, you or your apps user will really appreciate you putting that feature in your program. Well, I guess there is nothing more to add. Have fun!

Jason

Make Custom or Abnormal Shaped Forms in .NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

There may be a time when you get tired of the same old rectangle based form. You may even want to make the form a shape of a circle or work with skins. You needed to use Windows APIs to do it in 6.0. In VB.NET, Visual Basic 2008, VB 2010, and newer this is done pretty easily.


There are a few different ways to set your forms shape. I will use the GraphicsPath class in this article.

Variables/Objects to Make

  • new – GraphicPath
  • new – Region
  • new – StringFormat

    'Used to specify the Shapes, Text, and what-not.
    Dim p As Drawing2D.GraphicsPath = New Drawing2D.GraphicsPath

    'The region to pass to the form once its setup.
    Dim reg As Region

    'Used to specify the way to format the strings.
    Dim sf As New StringFormat

Once that is taken care of, specify what and how to display your forms region. In this example I am going to make the form a Ellipse shape and with a Text/String region as well.

        'Add a shape to display the region as.
        p.AddEllipse(0, 0, 100, 200) '

        'Add some text to display as well.
        p.AddString("Visual Basic for FREE!", FontFamily.Families.GetValue(1), FontStyle.Regular, 15, New Point(100, 100), StringFormat.GenericDefault)

        'Simply create a new Region object with the information in the Graphics Path.
        reg = New Region(p)

        'And the last is to set the newly created region for the form to display.
        Me.Region = reg

Results of the code in this article


That all there is to it. There are pretty much unlimited shapes you could make your form display as. This example works with Visual Basic.NET, Visual Basic 2008. VB 2010. and newer. Anyways, Have Fun!

Jason

Revised: 2015

Detecting if the User is Active or Idle – SystemWide using VB 6.0 and VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
 

There are times when you want to know not only if your user is interacting with your application but actually interacting anywhere on the computer. Especially if you are waiting for somekind of user Input. Microsoft thankfully made it easy as I found a API call on MSDN.com and I converted it from C++ to work with Visual Basic (Works for .NET, VB 2008/2010, VB 2013, and 2015). I actually have a VB 6.0 Example for doing this at my www.vbcodesource.com website. Below is the little API call…

Visual Basic 6.0

    '
    'The actual API call to use.
    Private Declare Function GetLastInputInfo Lib "user32.dll" (ByRef inputStructure As inputInfo) As Boolean
    '
    Private Type inputInfo

        structSize As Long

        tickCount As Long

    End Type

Visual Basic.NET Version…

    '
    'The actual API call to use.
    Private Declare Function GetLastInputInfo Lib "user32.dll" (ByRef inputStructure As inputInfo) As Boolean
    '
    Private Structure inputInfo

        Dim structSize As Int32

        Dim tickCount As Int32

    End Structure

Now that the APIs are out of the way, you only need to setup and use the codes. The code below will work for ALL VBs with just some minor changes…


Visual Basic 6.0

        '
        'The variable that will be passed to the API call and receive the activity report.
        Private info As inputInfo
        '
        'Visual Basic 5.0/6.0…
        Dim firstTick As Long
        Dim lastTick As Long

Visual Basic.NET…

        '
        'The variable that will be passed to the API call and receive the activity report.
        Private info As inputInfo
        '
        'Visual Basic.NET…
        '
        Dim firstTick As Int32
        '
        Dim lastTick As Int32

All I did next was use the code in a Timer control and set the Interval to 1000ms (1 Second) which will update the lblTime Label Control the Last time of day the user was active. The InputInfo structure will actually give you the tickcount for when the user was last active if you want to use that. I decided to simply get the actual time they were last active

        '
        'This timer will fire every 1000ms(One Second) or so displaying the last time the user was active.
        '
        'The size of the structure for the API call.
        info.structSize = Len(info)
        '
        'Call the API.
        GetLastInputInfo(info)
        '
        'Compare the tickcount values to determine if activity has occurred or not.
        If firstTick <> info.tickCount Then
            '
            'Display the current time of the users last activity.
            '
            'Change lblTime.Caption to lblTime.Text if using .NET and likewise change Time
            'to Now instead.
            lblTime.Caption = "Last Active: " & Time
            '
            'Get the new tick value.
            firstTick = info.tickCount

        End If

The example program wth the code in action


As I mentioned already, I put that code above in a Timer control, then I set to enable and disable the timer in Two Button controls.

Now your application will know when the user was last active on the computer. But remember, just because it says they are Not active doesn’t mean that they are not reading a document, a website, or some other task that doesn’t require user input. Have fun!

          Jason

Revised: 2015

Readymade Options for Playback of Music/Audio Files in VB and VB.NET – 1 of 2

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (10 votes, average: 3.90 out of 5)
 

This article and Part Two are to show some options available for Audio/Music playback if your not interested in making your own control or library. I do have an article on how to do basic music playback at this link with some quick and simple source code. But if you want more advanced features and don’t want to create the bulk of the playback code, then the content in these articles should help you out. This first article is on using some libraries I made around the MCISendString Windows API function and doesn’t have 3rd party dependency.

Note: You can now check out part two at this link on two 3rd party controls named Bass.dll and FMod.dll.


Visual Basic 6.0

For VB 6.0 is Music Module v2.2 that I made with Visual Basic 6.0 and contains the main features that a music player usually needs. It supports the most popular music formats like Wave, MIDI, and MP3 files. Some other features are calculating the MP3’s overall Bitrate, getting the Playing Position in various formats, Left/Right Volume Control with Muting, etc. While the class module is old, it still does the job well and does not rely on any 3rd Party .DLL’s or Resources. You can download the Class Module with Example at this link.

Visual Basic.NET 2002/2003

This option is basically for VB.NET 2002/2003 and would recommend you use it for those versions only. This library is called csMusicLibrary v1.0 Professional. This class contains more features than the VB 6 library.  The class has all of the features required for a normal music player and some extra features like basic playlist support, setting the music playback rate, setting the playing position and more. IF your interested in this option you can download the compiled class with example at this link.

Visual Basic 2005/2008/2010, and Higher

This next library definitely has the most features out of the options in this article. It is a major overhaul of the original csMusicLibrary. It is csMusicLibrary v3.1 – The Professional Series and made with Visual Basic 2005. It is completely XML commented with explanations about the Subs/Functions and Properties along with remarks. There are many options available and is easy to use and understand. Besides your normal playback features it can give your applications some basic recording capabilities, extract MP3 Tag v1.1 information, get the music playback status, and much more. Like the other options outlined above, this library does not rely on any 3rd party controls or resources. If you don’t need any super advanced features like visualizations, data manipulation, or sound effects, etc. then this library should work just fine for making a fully featured music application. You can download the compiled class with example at this link.


All these options should be fine for making a nice featured application. But you may be wanting more advanced features like FFT’s, Data Manipulation, Sound FX, and so on. That is where the next article will come in. Click this link to read part two about some third party controls. Have fun 🙂

Jason

Revised: 2014

Visual Studio 2005 IDE Enhancement Extensions

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 3.50 out of 5)
 

These resources are oldies but goodies. The enhancements are for version 2005 and includes a few different tools/resources or “Visual Studio Extensions”. Below is a overview as outlined by Microsoft…


Overview

Visual Studio 2005 IDE Enhancements are a set of Visual Studio extensions that are designed to make you more productive. These enhancements are directly integrated into the Visual Studio IDE. This set of enhancements includes Source Code Outliner, Visual C++ Code Snippets, Indexed Find, Super Diff and Event Toaster tools. All these tools except the IDE Event Toaster can be invoked from Visual Studio’s View.OtherWindows menu group. The Event Toaster tool can be configured from the Tools Options dialog under the PowerToys node. The Visual C++ Code Snippets can be invoked on any C++ source file. Previously, these enhancements were only available via the Visual Studio 2005 SDK. This installation does not require Visual Studio 2005 SDK.

Source Code Outliner : The Source Outliner tool is a Visual Studio extension that provides a tree view of your source code’s types and members and lets you quickly navigate to them inside the editor.

Visual C++ Code Snippets:The Visual C++ Code Snippets tool lets you insert snippets in your code by using a pop-up menu that contains programming keywords. VB.NET and C# languages have this functionality in Visual Studio 2005.

Indexed Find : The Indexed Find tool is a Visual Studio extension that uses the Microsoft Indexing Service to provide improved Search capabilities to the integrated development environment (IDE). It sends the results of a search to the Output Window.

Super Diff Utility: The Super Diff Find tool is a Visual Studio extension that compares text files. It uses color coding and graphics to show the difference between the files in deleted text (red), changed text (blue), inserted text (green).

Event Toaster Utility: The Event Toaster tool is a Visual Studio extension that notifies users about specific events within the Visual Studio IDE.

If you are interested in building your own Visual Studio extensions, you can download the Visual Studio 2005 SDK from here to get started.


So if you want these cool Extensions, just click this link to head over to the Microsoft Download page.

Jason

Why Simply Calling ExitWindowsEx won’t Shutdown or Restart Windows XP, Vista, 7, and Newer

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
 

Simply executing the ExitWindowsEx API function works fine using older versions of Windows like Windows 98 or ME. You only needed to call the ExitWindowsEx with the desired parameters and it was good to go. But with the regular consumer family of Windows starting with Windows XP, Microsoft based the OS on NT/2000 which is a very different Kernel and Architecture. That includes Windows Vista, Windows 7, 8/8.1, and 10 as well. Your programs are now required to have ‘special privileges’ before it will grant your application’s request to shutdown/restart/logoff the device. Visual C++ has these Privileges by default, but not any of the VBs unfortunately. So the first step you must do is request your application be granted the required privileges. The source code below was originally in VB 6.0 code from Microsoft that I converted to Visual Basic .NET. The code here will work with all versions of .NET including 2005, 2008, plus Visual Basic 2010, and newer. There are only minor changes needed to make it work with Visual Basic 6.0, mainly the variable/parameter types like changing the Integers to Long types. I went ahead and put the VB.NET source code in this post.

Note: If you are wanting to get the original VB 6.0 privilege codes then click on this link and/or click this link as well.

Need to first get some structures for the APIs.

    Private Structure LUID

        Dim UsedPart As Integer

        Dim IgnoredForNowHigh32BitPart As Integer

    End Structure

    Private Structure TOKEN_PRIVILEGES

        Dim PrivilegeCount As Integer

        Dim TheLuid As LUID

        Dim Attributes As Integer

    End Structure

Next you can go ahead and add the needed API methods to execute the privilege requests.

    '
    'The API functions below are all used to give the application the proper privilege so the OS will allow the app to Shutdown Windows.
    '
    Private Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As IntPtr, ByVal DesiredAccess As Integer, ByRef TokenHandle As Integer) As Integer

    Private Declare Function LookupPrivilegeValue Lib "advapi32" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, ByRef lpLuid As LUID) As Integer

    Private Declare Function AdjustTokenPrivileges Lib "advapi32" (ByVal TokenHandle As Integer, ByVal DisableAllPrivileges As Boolean, ByRef NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Integer, ByRef PreviousState As TOKEN_PRIVILEGES, ByRef ReturnLength As Integer) As Integer

Now to setup and create a Sub that will do all the work to set your privileges.

    '
    'This sub will do all of the work of setting up your apps process using the APIs posted above to get the
    'proper privileges to shutdown the OS.
    'I originally got this function from msdn and converted it from VB 6.0 to VB.Net and did a tweak here and there.
    '
    Private Sub AdjustToken()

        Const TOKEN_ADJUST_PRIVILEGES As Int32 = &H20

        Const TOKEN_QUERY As Int32 = &H8

        Const SE_PRIVILEGE_ENABLED As Int32 = &H2

        Dim hdlProcessHandle As IntPtr

        Dim hdlTokenHandle As Int32

        Dim tmpLuid As LUID

        Dim tkp As TOKEN_PRIVILEGES

        Dim tkpNewButIgnored As TOKEN_PRIVILEGES

        Dim lBufferNeeded As Int32

        hdlProcessHandle = Process.GetCurrentProcess.Handle

        OpenProcessToken(hdlProcessHandle, (TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY), hdlTokenHandle)

        'Get the LUID for shutdown privilege.
        LookupPrivilegeValue("", "SeShutdownPrivilege", tmpLuid)

        tkp.PrivilegeCount = 1 'One privilege to set

        tkp.TheLuid = tmpLuid

        tkp.Attributes = SE_PRIVILEGE_ENABLED

        'Enable the shutdown privilege in the access token of this process.
        AdjustTokenPrivileges(hdlTokenHandle, False, tkp, Len(tkpNewButIgnored), tkpNewButIgnored, lBufferNeeded)

    End Sub

Now that the main Privilege codes are done, you just need one more API Function.

Below is the API call you execute to perform the actual shutdown/restart/logoff command on the computer.

    'The function used to actually send the request to shutdown windows. Set the ‘shutdownTypes’ parameter to whether you want windows to “shutdown, reboot, logOff, ect…” You can get those at MSDN or download one of my examples from my VBCodesource.com website.
    Private Declare Function ExitWindowsEx Lib "user32" (ByVal shutdownType As Integer, ByVal dwReserved As Integer) As Integer

Edit: As per Garry’s comment below, I included some relevant flags you can use with the ExitWindowsEx function.

        Private Const EWX_LOGOFF As Integer = &H0
        Private Const EWX_SHUTDOWN As Integer = &H1
        Private Const EWX_REBOOT As Integer = &H2
        Private Const EWX_FORCE As Integer = &H4
        Private Const EWX_POWEROFF As Integer = &H8
        Private Const EWX_FORCEIFHUNG As Integer = &H10 '2000/XP only

OK, now you first need to call the AdjustToken()  Sub and then the ExitWindowsEx Function. This example code will Log Off the user.

        AdjustToken()

        'Calls the function to begin executing.
        ExitWindowsEx(EWX_LOGOFF, Nothing)

That’s all there is to it! OK, it Is a lot of code to get the ExitWindowsEx API to work with Windows 2000/XP/Vista/7/8/8.1/10.0. To bad Microsoft doesn’t give Visual Basic these Privileges by default like they do with C++. Oh well, don’t have much of a choice.

Remember, its possible to get these codes to work with Visual Basic 6.0 as well. You need to change the types (Especially Integers to Longs, and Structures to Types) plus process info then it should be ok. Or click on this link to the original code

I have pre-made Class Libraries and Examples for Visual Basic.NET, VB 2005/2008/2010/2012, and Visual Basic 2013. I also have an Example of doing this in Visual Basic 6.0 at my Visual Basic Code Source website.

Well that’s all for now. Have Fun!

Jason

Revisited: 2015

FREE eBook – Upgrading Microsoft Visual Basic 6.0 to Microsoft Visual Basic .NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 1.00 out of 5)
 

This is another resource that how been around for awhile but is still plenty useful and helpful. Especially if your a Visual Basic 5.0/6.0  developer making the move to Visual Basic.NET. It is pretty large and covers a wide range of areas taking up TwentyOne(21x) Chapters. It goes over The differences between VB Classic and .NET to Resolving Upgrade Issues and Preparing your Applications for the Upgrade. Below is a small excerpt…


Excerpt…

Upgrading Microsoft Visual Basic 6.0 to Microsoft Visual Basic .NET is the complete technical guide to upgrading Visual Basic 6 applications to Visual Basic .NET, covering all upgrade topics from APIs to ZOrders. It shows how to fix upgrade issues with forms, language, data access, and COM+ Services, and how to upgrade applications with XML Web services, ADO.NET, and .NET remoting. It also provides big-picture architectural advice, a reference of function and object model changes, hundreds of before-and-after code samples, and a CD packed with useful examples.


If you are interested in this resource, then click this link to check it out. Try this link as well. Have fun 🙂

Jason

Find out how many CPU’s/Processors/Cores the computer has installed using VB.NET and Higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

Its actually very easy with Visual Basic.NET VB 2008, VB.NET 2010, 2013, and Higher to detect the cpu or core count for the computer. Below is the very simple way to do it which will return the total number of logical processors installed in the computer…

        '
        'This works for Visual Basic 2005 and Higher.
        '
        'The code we want is under the System.Environment Namespace and is the ProcessorCount
        'property.
        MsgBox(System.Environment.ProcessorCount.ToString)

What if you want to get the CPU/Processor/Core count with Visual Basic.NET 2002 or 2003?

Well, .NET version 1.1 and older does not have the ProcessorCount property like version 2.0 of the .NET Framework. But that doesn’t mean it can’t be done. Its actually not to awfully hard to do. Below is a way to do it using the Windows system Registry…

        '
        'The registry path to get the info we are wanting.
        Dim str As String = "HARDWARE\DESCRIPTION\System\CentralProcessor"
        '
        'Returns how many SubKeys are under “CentralProcessor”. The subKey count under this key
        '=’s the‘total cpu’s your system has installed. Of course, 90% or so will only have 1x
        'subkey denoting a ‘single cpu system. My system happens to return 2x subkeys since I
        'have a Dual Core system.
        Dim cpuCount As Integer = My.Computer.Registry.LocalMachine.OpenSubKey(str, False).SubKeyCount

        MsgBox(cpuCount.ToString)

The Messagebox will then throw a Dialog with the total number of cpu’s/core’s on the current computer. I do not know though if this works on all Windows operating systems.

You can also use the Windows Management Instrumentation (WMI) and get the total instances of the class.

Below is a simple way to use WMI to return the computers CPU/Core Count…

       '
        'Create a Instrument Class and Object.
        Dim wmiClass As New System.Management.ManagementClass
        Dim wmiObject As New System.Management.ManagementObject
        '
        'Set the PAth to “Win32_Processor” which is where we want to get info.
        wmiClass.Path.RelativePath = "Win32_Processor"
        '
        'Last of all, just check how many instances is available and that will be your cpu/core count.
        MsgBox(wmiClass.GetInstances.Count)

Executing the code above will tell you how many cpus are on the computer since there is a class instance for each CPU/processor/core on the current computer.

Take care 🙂

                       Jason

Revised: 2015

Easy way to take a screenshot in VB 2008 and Visual Basic.NET 2010

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

The newer 2.0 version of the DotNET Framework added alot of new features. One of them is the ability to natively copy the visual contents of the screen. You can find this Sub() under the: System.Drawing.Graphics namespace named – ‘CopyFromScreen’. The ‘CopyFromScreen’ Sub has 4x overloads. You can specify the Destination coordinates to put the image and the Source coordinates to get the image. Also available is CopyPixelOperation which allows you to select the way you want to copy the pixels. System.Drawing.CopyPixelOperation.SourceCopy is the most common operation. Below is a simple demonstration to take a screenshot in your applications.

This basic sample only needs a picturebox.


'Copy the screen contents to the picturebox control. Select the X and Y positions to get the‘screens image,
'then select the X,Y positions to set the screen image to the picturebox control.
'You then simply specify how much of the image you want to copy. picScreen is the name of the picturebox I used.

picScreen.CreateGraphics.CopyFromScreen(0, 0, 0, 0, New Size(100, 100))

How to make a single instance application in VB.NET 2003 and Older

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 3.00 out of 5)
 

Visual Basic.NET 02/03 didn’t keep the Instance features that VB 6.0 had which was App.Previnstance. Not sure why they didn’t add a simple feature like that, but they didn’t. That simple code lets you know if your app is already open and then you can decide on what to do about the app.Preinstance results. So, for VB.NET 2002/2003 we have to be a little intuitive. Its really not that hard though once you understand the concept. Below is some simple code that will do this for you. Its taken from my code snippets page by the way. 🙂

Update: 2010, February 19th: Maxim mentioned about a different solution to this problem. Its more thorough and elegant. Check out this link to see his solution…



    Private Function preInstanceCheck() As Boolean
        '
        'This uses the Process class to check for the name of the current
        'applications process and ‘see whether or not there are more than 1x instance loaded.
        'The end result of this code is similar to Visual Basic 6.0’s App.Previnstance feature.
        Dim appName As String = Process.GetCurrentProcess.ProcessName
        Dim sameProcessTotal As Integer = Process.GetProcessesByName(appName).Length
        '
        'If the total is higher than 1 there is of course a duplicate instance already running.
        If sameProcessTotal > 1 Then

            MessageBox.Show("A previous instance of this application is already open!", _
                " App.PreInstance Detected!", MessageBoxButtons.OK, _
                MessageBoxIcon.Information)
            '
            'A duplicate instance is found. You can close the application or
            'whatever it is you want to do.
            'Me.Close()

            Return True

        Else

            Return False

        End If

    End Function

Revisited: 2015

Get the Operating System: Name, Platform, Version, and Service Pack using VB.NET 2008 and higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

This will return the Windows Operating System Name, Platform, and Version using the MY interface under VB 2008, Visual Basic 2010, and 2013. Then from the System.Environment class it will get the operating systems installed Service Pack, and then the entire OS info in one string value.

'This will throw 5x messageboxes with the FullName of the Installed Windows, along with
'the OS Platform, OS Version, the service pack installed, and then a message show all
'of the information about windows. that your program is running on. This works with VB 2005,
'Visual Basic.NET 2008, and Visual Basic 2010
'
MsgBox(My.Computer.Info.OSFullName)
 
MsgBox(My.Computer.Info.OSPlatform.ToString)
 
MsgBox(My.Computer.Info.OSVersion.ToString)
 
MsgBox(Environment.OSVersion.ServicePack)
 
MsgBox(Environment.OSVersion.VersionString)

Revised: 2015