Archives

Archives / 2003 / May
  • VS.NET and editing Resx files

    Am I missing something or is it really true that the built-in resource editor in VS.NET only supports strings? I can't find anyway to put binary files (for example, a bitmap) into a ResX in VS.NET's resource editor. Thankfully, there's Lutz Roeder's Resourcer.

  • VB.NET: Under The Covers

    Being a curious kind of guy, I decided to look into some of the features unique to VB.NET.  A combination of some VB.NET code, ILDASM and Anakrino and my questions were answered!

  • Static Local Variables in VB.NET

    VB.NET has support for "local static variables". These are variables local to a method, but retain their method call between invocations of the method. The CLR does not support this, so how does VB.NET do it if it runs under the CLR? Just some simple compiler tricks!

  • Catching Windows messages

    I needed to capture mouse clicks before my windows app got a hold of them.  Seeing that the Form class has a PreProcessMessage method I thought I was all set.  As the documentation stated:

  • Moving a form by clicking anywhere on it.

    You've seen applications that allow you to move the form around by simply clicking anywhere on the form (not just the caption bar). Can you do this in .NET? Yes! And it's very easy. All you have to do is handle the proper windows message and the rest is easy.

    Option Strict On
    Option Explicit On
    
    Imports System Imports System.Windows.Forms Imports System.Drawing
    Public Class Form1 Inherits Form
    Private Declare Function ReleaseCapture Lib "user32" () As Long Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
    Private Const WM_NCLBUTTONDOWN As Integer = &HA1 Private Const HTCAPTION As Integer = 2
    Public Sub New() Me.Text = "Drag anywhere to move" AddHandler Me.MouseDown, AddressOf frmMain_MouseDown End Sub
    <STAThread()> _ Shared Sub Main() Application.Run(New Form1()) End Sub
    Private Sub frmMain_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) 'Don't drag the sceen if it is the right button or the wheel. If e.Button = MouseButtons.Left Then ReleaseCapture() SendMessage(Me.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0) End If
    End Sub
    End Class

  • Browsing for a folder (1.0)

    Still using the .NET 1.0 framework and need a "browse for folder" dialog? You'll need to resort to platform invoke (p/invoke) using the Win32 API's. Here's a class that encapsulates all of it.

  • Pulling a bitmap off the clipboard.

    Here's an example of pulling a bitmap off the clipboard and displaying it in a windows form.

    Option Strict On
    Option
     Explicit On 

    Imports System
    Imports System.Windows.Forms
    Imports System.Drawing

    Public Class WinApp
        
    Inherits System.Windows.Forms.Form

        
    Private m_PB As PictureBox

        <STAThread()> _
        
    Shared Sub Main()
            Application.Run(
    New WinApp())
        
    End Sub

        Public Sub New()
            
    Me.Text = "This is my form"
            m_PB = New PictureBox()
            m_PB.Location = 
    New Point(0, 0)
            m_PB.Size = 
    Me.Size

            m_PB.Image = GetImageFromClipboard()
            
    If Not m_PB.Image Is Nothing Then
                Me.ClientSize = New Size(m_PB.Image.Width, m_PB.Image.Height)
                m_PB.Size = 
    Me.ClientSize
            
    End If

            Me.Controls.Add(m_PB)
        
    End Sub

        Public Function GetImageFromClipboard() As Image
            
    If Not Clipboard.GetDataObject() Is Nothing Then
                Dim dobj As IDataObject = Clipboard.GetDataObject()
                
    If dobj.GetDataPresent(DataFormats.Bitmap) Then
                    Dim img_obj As Object = dobj.GetData(DataFormats.Bitmap)
                    
    Return CType(img_obj, Bitmap)
                
    End If
            End If
        End Function

    End
     Class

  • Adjusting to life without ItemData

    In VB6, the ListBox and ComboBox controls had the ItemData property. This was a “companion” list of long integers which could be used to store additional information related to an Item. For example, you could display a list of individuals in a ListBox and keep their age in the ItemData property:

  • Creating an image from a URL.

    This example shows how you can download and create an Image based on a URL.

    Option Strict On
    Option Explicit On
    
    Imports System Imports System.Windows.Forms Imports System.Drawing Imports System.Net Imports System.IO
    Public Class WinApp Inherits System.Windows.Forms.Form
    <STAThread()> _ Shared Sub Main Application.Run(new WinApp()) End Sub
    Dim m_pb As PictureBox
    Public Sub New Me.Text = "This is my form"
    m_pb = new PictureBox() m_pb.Location = new Point(0,0) m_pb.Image = GetURL("http://radio.weblogs.com/0110109/images/dotnet.gif") m_pb.Size = m_pb.Image.Size Me.ClientSize = m_pb.Image.Size
    Me.Controls.add(m_pb) End Sub
    Private Function GetURL(url as String) As Bitmap Dim wc As WebClient = new WebClient() Dim strm As Stream = wc.OpenRead(url) Dim bmp As BitMap = new Bitmap(strm)
    strm.Close() Return bmp End Function
    End Class

  • Enumerate Network Adapters

    This sample enumerates all of the installed network adapters to reveal such information as MAC address, IP Address, IP Subnet, etc...

    '
    ' base on C# code originally posted by Willy Denoyette
    http://groups.google.com/groups?selm=eeeD%24NrxAHA.2188%40tkmsftngp02
    '
    Option Strict On
    Option
     Explicit On

    Imports
     System
    Imports System.Management

    Public Class ConsoleApp

       
    Shared Sub Main
          Network.EnumNetworkAdapters()
       
    End Sub
       
    End Class
       
    Public Class Network
       
    Public Shared Sub EnumNetworkAdapters()
          
    Dim query as ManagementObjectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration")
          
    Dim queryCollection as ManagementObjectCollection  = query.Get()
          
    Dim mo as ManagementObject
          
    Dim s as String
          
          
    for each mo in queryCollection
               Console.WriteLine( 
    "'{0}'", mo.ClassPath)
               Console.WriteLine( 
    "'{0}'", mo.Options)
               Console.WriteLine( 
    "Index   '{0}'", mo("Index"))
               Console.WriteLine( 
    "Description   '{0}'", mo("Description"))
               Console.WriteLine( 
    "MacAddress   '{0}'", mo("MacAddress"))
               
               
    if(CType(mo("IPEnabled"), Boolean) = true)
                   
    dim addresses() as string = CType(mo("IPAddress"), String())
                   
    dim subnets() as string = CType(mo("IPSubnet"), String())
                   
                   Console.WriteLine( 
    "DNS Host   '{0}'", mo("DNSHostName"))
                   Console.WriteLine( 
    "DNS Domain   '{0}'", mo("DNSDomain"))
                   
                   
    for each s in addresses
                       Console.WriteLine( 
    "IP Address   '{0}'", s)
                   
    next
                   
                   
    for each s in subnets
                       Console.WriteLine( 
    "IP Subnet   '{0}'", s)
                   
    next
               end if
          next
       End Sub
    End
     Class

  • OPML Swapping

    Something I just noticed: If you've got a bunch of subscriptions in RSS Bandit and want to play around with SharpReader, the OPML format exported by RSS Bandit is not immediately usable by SharpReader.  I'm not up on the OPML format so I don't know which program is at fault, but there's a simple fix:

  • Using VB.NET Objects in regular ASP Pages

    Using a VB.NET object in an ASP page can be accomplished with COM-Interop. While the whole interop mechanism can be complex depending on what you want to do, below is a basic example that should get you started.

    1. Create a file called Class1.vb and placed this code in it:

    Public Class SampleClass
    
        Public Function GetMyName() As String
    
            Return "This is from the .NET component"
    
        End Function
    
    End Class
    


    2. Create a keyfile with the strong name (sn) utility:
    sn -k demokey.snk
    3. Compile the VB app with:
    vbc /t:library /keyfile:demokey.snk class1.vb
    4. Install the library into the GAC with:
    gacutil -i class1.dll
    5. Use RegAsm to register it as a COM class:
    regasm /tlb:class1.tlb class1.dll
    Test it in ASP with:

    <%
    set x = server.CreateObject("SampleClass")
    response.Write x.GetMyName()
    %>

  • RSS Bandit Comments

    Now that's I've dumped Radio, I'm looking for a news aggregator.  I worked a little with RSS Bandit this morning.  A nice little app.  A few things I'd like to see:

  • URL Encoding in Windows Forms

    If you need to do some URL encoding in a Windows Forms app, the HttpUtility class has a shared (static) method to URL encode a string. Below is a sample.

    NOTE: The HttpUtility class also contains a shared (static) HTML encoder too!

    Option Strict On
    Option
     Explicit On

    Imports
     System
    Imports System.Windows.Forms
    Imports System.Drawing
    Imports System.Web

    Public Class WinApp
        
    Inherits System.Windows.Forms.Form

        
    private m_url as TextBox

        <STAThread()> _
        
    Shared Sub Main
            Application.Run(
    new WinApp())
        
    End Sub

        Public Sub New
            Me.Text = "URL Test"

            m_url = New TextBox()
            m_url.Size = 
    new Size(280,30)
            m_url.Location = 
    new point (5,5)

            Controls.Add(m_url)
            m_url.Text = 
    "http://www.microsoft.com?value="; & HttpUtility.UrlEncode("encode me please")
        
    End Sub

    End
     Class

  • Getting RTF Text off the clipboard.

    Need to get RTF text off the clipboard? Use the IDataObject interface to see if there is RTF data on the clipboard. In the sample below, copy some RTF data onto the clipboard from another application then simply click anywhere on this form to see the actual RTF string data.

    Option Strict On
    Option
     Explicit On

    Imports
     System
    Imports System.Windows.Forms
    Imports System.Drawing
    Imports Microsoft.VisualBasic

    Public Class Form1
        
    Inherits Form

        
    Public Sub New()
            
    Me.Text = "Clipboard Test"
            AddHandler Me.Click, AddressOf MouseClick
        
    End Sub

        Public Sub MouseClick(byval sender As objectbyval e As EventArgs)
            
    If Not Clipboard.GetDataObject() Is Nothing
                Dim dobj As IDataObject = Clipboard.GetDataObject()
                
    If dobj.GetDataPresent(DataFormats.RTF) then
                    Dim rtfobj As Object = dobj.GetData(DataFormats.RTF)
                    MsgBox(rtfobj.ToString())
                
    End if
            End if
        End Sub

        <STAThread()> _
        
    Shared Sub Main()
            Application.Run(
    New Form1())
        
    End Sub
    End
     Class

  • Detecting a click on the caption bar.

    Need to detect a click on the caption bar? You can easily intercept the required windows message (WM_NCLBUTTONDOWN).

    Option Strict On
    Option
     Explicit On

    Imports
     System
    Imports System.Windows.Forms
    Imports System.Drawing

    Public Class Form1
        
    Inherits Form

        
    Private ReadOnly WM_NCLBUTTONDOWN As Integer = &HA1

        
    Public Sub New()
            
    Me.Text = "Window Caption"
        End Sub

        Protected Overrides Sub WndProc(ByRef m As Message)
            
    If m.msg = WM_NCLBUTTONDOWN Then
                Console.WriteLine("caption click...")
            
    End if
            MyBase.WndProc(m)
        
    End Sub

        <STAThread()> _
        
    Shared Sub Main()
            Application.Run(
    New Form1())
        
    End Sub
    End
     Class

  • Create and display a form based on its Name

    This sample uses Reflection to create a form using only the name stored in a string. While the technology can do way more than what is presented in this example, this will give you a basic start. Note that in this example, an instance of Form2 is created and shown based only on the string "Form2" when the main form is clicked on.

    Option Strict On
    Option
     Explicit On

    Imports
     System
    Imports System.Windows.Forms
    Imports System.Drawing

    Public Class Form1
        
    Inherits Form

        
    Public Sub New()
            
    Me.Text = "Main Form"
            AddHandler Me.Click, AddressOf FormClick
        
    End Sub

        Public Sub FormClick(byval sender As Objectbyval e As Eventargs)
            
    Dim myType As Type = Type.GetType("Form2")
            
    Dim myForm As Form

            
    Dim newForm As Object = Activator.CreateInstance(myType)
            myForm = 
    CType(newForm, Form)
            myForm.Show()
        
    End Sub

        <STAThread()> _
        
    Shared Sub Main()
            Application.Run(
    New Form1())
        
    End Sub
    End
     Class

    Public
     Class Form2
        
    Inherits Form

        
    Public Sub New()
            
    Me.Text = "Second Form"
        End Sub
    End
     Class