Exposing Windows Forms Controls as ActiveX controls

來源:互聯網
上載者:User
文章目錄
  • Inserting the Control
  • Testing Methods
Introduction
  • Download demo project - 15 Kb

This article will describe how to utilise Windows Forms controls outside of .NET. In a recent MSDN magazine article on .NET Interop available here, various ways of exposing .NET objects to 'legacy' environments are discussed, including the exposure of Windows Forms controls as ActiveX controls.

The problem is that the goalposts have moved since the article was written as Beta 2 is now available, and unfortunately this support has been removed - see this posting on the .NET list at http://discuss.develop.com.

The following image shows a control, written purely within .NET, hosted within an ActiveX control container - in this instance tstcon32.exe.

As Beta1 supported this facility, and being somewhat inquisitive, I decided to see if I could find a way to expose controls anyway. The attached project creates the 'Prisoner' control, which won't set the world on fire but does show the main things you need to do in order to get a .NET control up & running within VB6.

CAVEAT: As this support has been dropped from Beta2 of .NET, don't blame me if it fries your PC or toasts the cat.

Now that's out of the way, how's it done?.

Writing the control
  1. Create a new control project from within Visual Studio - my examples are all in C# but VB.NET could also be used.

     

  2. Add controls etc to the form, put in the code etc.

     

  3. Add in the following using clauses...

     

    <span class="cs-keyword">using</span> System.Runtime.InteropServices;    <span class="cs-keyword">using</span> System.Text;    <span class="cs-keyword">using</span> System.Reflection;    <span class="cs-keyword">using</span> Microsoft.Win32;
  4. Attribute your class so that it gets a ProgID. This isn't strictly necessary as one will be generated, but it's almost always best to be explicit.
    [ProgId(<span class="cs-string">"Prisoner.PrisonerControl"</span>)]    [ClassInterface(ClassInterfaceType.AutoDual)]

    This assigns the ProgID, and also defines that the interface exposed should be 'AutoDual' - this crufts up a default interface for you from all public, non-static members of the class. If this isn't what you want, use one of the other options.

  5. Update the project properties so that your assembly is registered for COM interop.

     

    If you're using VB.NET, you also need a strong named assembly. Curiously in C# you don't - and it seems to be a feature of the environment rather than a feature of the compiler or CLR.

  6. Add the following two methods into your class.

     

    Collapse
    [ComRegisterFunction()]    public static void RegisterClass ( string key )    {    // Strip off HKEY_CLASSES_ROOT\ from the passed key as I don't need it    StringBuilder sb = new StringBuilder ( key ) ;    sb.Replace(@"HKEY_CLASSES_ROOT\","") ;    // Open the CLSID\{guid} key for write access    RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(),true);    // And create the 'Control' key - this allows it to show up in     // the ActiveX control container     RegistryKey ctrl = k.CreateSubKey ( "Control" ) ;    ctrl.Close ( ) ;    // Next create the CodeBase entry - needed if not string named and GACced.    RegistryKey inprocServer32 = k.OpenSubKey ( "InprocServer32" , true ) ;    inprocServer32.SetValue ( "CodeBase" , Assembly.GetExecutingAssembly().CodeBase ) ;    inprocServer32.Close ( ) ;    // Finally close the main key    k.Close ( ) ;    }    

    The RegisterClass function is attributed with ComRegisterFunction - this static method will be called when the assembly is registered for COM Interop. All I do here is add the 'Control' keyword to the registry, plus add in the CodeBase entry.

    CodeBase is interesting - not only for .NET controls. It defines a URL path to where the code can be found, which could be an assembly on disk as in this instance, or a remote assembly on a web server somewhere. When the runtime attempts to create the control, it will probe this URL and download the control as necessary. This is very useful when testing .NET components, as the usual caveat of residing in the same directory (etc) as the .EXE does not apply.

    [ComUnregisterFunction()]    <span class="cs-keyword">public</span> <span class="cs-keyword">static</span> <span class="cs-keyword">void</span> UnregisterClass ( <span class="cs-keyword">string</span> key )    {    StringBuilder sb = <span class="cs-keyword">new</span> StringBuilder ( key ) ;    sb.Replace(@<span class="cs-string">"HKEY_CLASSES_ROOT\"</span>,<span class="cs-string">""</span>) ;    <span class="cs-comment">// Open HKCR\CLSID\{guid} for write access</span>    RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(),<span class="cs-keyword">true</span>);    <span class="cs-comment">// Delete the 'Control' key, but don't throw an exception if it does not exist</span>    k.DeleteSubKey ( <span class="cs-string">"Control"</span> , <span class="cs-keyword">false</span> ) ;    <span class="cs-comment">// Next open up InprocServer32</span>    RegistryKey inprocServer32 = k.OpenSubKey ( <span class="cs-string">"InprocServer32"</span> , <span class="cs-keyword">true</span> ) ;    <span class="cs-comment">// And delete the CodeBase key, again not throwing if missing </span>    k.DeleteSubKey ( <span class="cs-string">"CodeBase"</span> , <span class="cs-keyword">false</span> ) ;    <span class="cs-comment">// Finally close the main key </span>    k.Close ( ) ;    }

    The second function will remove the registry entries added when (if) the class is unregistered - it's always a good suggestion to tidy up as you go.

Now you are ready to compile & test your control.

Testing the Control

For this example I have chosen tstcon32.exe, which is available with the installation of .NET. The main reason I've used this rather than VB6 is that I don't have VB6 anymore.

Inserting the Control

First up you need to insert your control, so to do that choose Edit -> Insert New Control, and choose your control from the dropdown...

This will result in a display as shown at the top of the article, if you're following along with my example code.

Testing Methods

The example control only includes one method, 'Question'. To test this within TstCon32, choose Control -> InvokeMethods from the menu, and select the method you want to call. Note that because I defined the interface as AutoDual, I get gazillions of methods. If you implement an interface and expose this as the default interface then the list of methods will be more manageable.

Click on the 'Invoke' button will execute the method, which in this instance displays the obligatory message box.

Wrap Up

Dropping support for creating ActiveX controls from Windows Forms controls is a pain, and one decision I wish Microsoft had not made.

This article presents one way of exposing .NET controls as ActiveX controls, and seems to work OK. Having said that, I've not exhaustively tested this and who knows what bugs might be lurking in there. I haven't delved into events yet, nor property change notifications, so there's some fun to be had there if you like that sort of thing.

The .NET framework truly is the best thing since sliced bread, but the lack of support for creating ActiveX controls from Windows Forms controls is inconvenient. There are many applications out there (ours included) which can be extended with ActiveX controls. It would be nice given the rest of the support in the framework to be able to expose Windows Forms controls to ActiveX containers, and maybe someday the support will be available.


About Morgan Skinner

Now working in Microsoft Developer Services, based in the UK.

I loved .NET so much I had to join the company!.

Click here to view Morgan Skinner's online profile.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.