Get Current logged on Username – – using advapi32.dll

Note this codes about 6 years old as of 2014 – I’m sure there are better ways of doing this now but this worked at the time and is still live in one of my projects.

I needed to identify the currently logged on user running my application to make an audit file and also show only user options that the logged on user was setup for.

Here’s the code…

Declare Function GetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, _
ByRef nSize As Integer) As Integer

   Public Function GetUserName() As String
        'Gets currently logged on user - username
        Dim iReturn As Integer
        Dim userName As String
        'put the username in a string limit 50 chars
        userName = New String(CChar(" "), 50)
        'put the length of the username in an Integer iReturn
        iReturn = GetUserName(userName, 50)
        'Tidy up various formatting if required with the replace function like remove the .
        userName = userName.Replace("."c, " "c)
        'Return the username back
        GetUserName = userName.Substring(0, userName.IndexOf(Chr(0)))

    End Function

Using WMI Code Creator for projects

WMI Code Creator v1.0 – Download Here
Allows you to browse the available WMI classes and create query’s that can be used either through command-line through visual basic script or in your .NET projects.

Once you have your query you can then export the code for Visual C# or Visual Basic.

I used this program to create some code for a quick way of viewing installed printers on a remote print server in Visual C# by populating the results to a datagrid.

                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = userName.Text;
                connection.Password = password.Text;
                connection.Authority = "ntlmdomain:DOMAINNAME";
                ManagementScope scope = new ManagementScope(
                    "\\\\" + serverName.Text + ".FullyQualifiedDomainName\\root\\CIMV2", connection);

                ObjectQuery query = new ObjectQuery(
                    "SELECT * FROM Win32_Printer"); 

                ManagementObjectSearcher searcher =  new ManagementObjectSearcher(scope, query);

                    DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
                    row.Cells[0].Value = queryObj["DeviceID"];
                    row.Cells[1].Value = queryObj["DriverName"];
                    row.Cells[2].Value = queryObj["Location"];
                    row.Cells[3].Value = queryObj["Name"];
                    row.Cells[4].Value = queryObj["Comment"];
                    row.Cells[5].Value = queryObj["Portname"];
                    row.Cells[6].Value = queryObj["SystemName"];
            catch (ManagementException e)
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);

Fast and effective to what I needed – Instead of trying to copy all the printer details out in to excel.

Scraping webpages and displaying data from it…

When you are working on a project to get data from a webpage but you don’t have access to the back-end database or a API to get any values out.

The workaround I use until something changes is Web scraping.

I have a project with this problem – it’s another VB.NET one.

My Scraping code goes along like this –

'Get the URL / Navigate a browser window too it (this is hidden in my project

'Convert the HTML of the page to a string using the body.outerhtml function
webPage1 = WebBrowser.Document.Body.OuterHtml

'Use the InString function to search for a term in the webPage1 string
If InStr(webPage1, "term to search") <> 0 Then
'get the position of the term to search
            StringSearch = InStr(webPage1, "term to search")
'pick some deatails out of the page using the position + x and capture the next n letters
            ScrapedText = Mid(webPage1, StringSearch + x, n)
'tidy up anything we don't like out of the returned string 
            ScrapedText = ScrapedText.Replace(".", "")
'now we have the scraped text we can use it in our app

        End If

Ta-da – workaround using scraping.

Resizing using smartsize with AxMsRdpClient (Microsoft Terminal Services Control Type Library COM)

I’ve been using the AxMsRdpClient from Microsoft Terminal Services Control Type Library COM (Imported from AxInterop.MSTSCLib) in a project through Visual Studio 2010 using VB.NET

and found the only way to re-size the RDP window via smart size is after making a connection at full size to the RDP and then forcing the size down.

This took me a good hour to work out since I can’t find any examples of this online.

I’m sharing this as it may help someone else looking to work with AxMsRdpClient

Private Sub ConnectScreen1_Click(sender As System.Object, e As System.EventArgs) Handles ConnectScreen1.Click
        ''Check if we are already connected to a RDP session - If so Return 
        If AxMsRdpClient8NotSafeForScripting1.Connected = 1 Then Return

        ''specify the server the RDP is going to connect up
        AxMsRdpClient8NotSafeForScripting1.Server = Settings.Default.RDP1
        AxMsRdpClient8NotSafeForScripting1.Height = 768
        AxMsRdpClient8NotSafeForScripting1.Width = 1024
        AxMsRdpClient8NotSafeForScripting1.ConnectingText = "Connecting..."

        ''enable smart sizing
        AxMsRdpClient8NotSafeForScripting1.AdvancedSettings7.SmartSizing = True

        ''connect up the RDP session
        ''now resize
        AxMsRdpClient8NotSafeForScripting1.Height = 580
        AxMsRdpClient8NotSafeForScripting1.Width = 760
    End Sub