Welcome to MSDN Blogs Sign in | Join | Help

Properties and Methods

Now that we have a simple control hosted in the WebBrowser, it would be nice to be able to interact with it from the page.  Using JavaScript, we can call methods on the managed control, and also get/set properties (which are essentially just method calls themselves).

We'll expand our simple control from before to include a property "ThemedBackgroundColor" and a method "SayHello" and then call them from JavaScript on the page.

A couple of things to notice about my sample implementation.

1.  I have introduced new properties and methods for my interactions even when the ones defined on System.Windows.Forms.Control might suffice.  I do this so that I can explicitly control the interactions between script and my control.  Soon, we will restrict all interactions to a defined interface to make this more explicit.

2.  I have used the string type for my color property rather than the System.Drawing.Color type.  I do this because JavaScript is a "stringy" language and I want to provide properties and methods that are as friendly as possible to the script world.  (Internally I use the System.Drawing.ColorTranslator to convert between these strings and the managed Color instances that I want).

Here is where we stand right now:

Host.html

<html>
  <head><title>Simple control host</title></head>
<body>
  <H1>Simple control host page</H1>
  <object id=simpleControl width=200 height=200 classid="SimpleControl.dll#SimpleControl"></object>
  <br>
  <a href="javascript:simpleControl.SayHello();">Say Hello</a>
  <br>
  <input type=text id=colorName value="Green"><input type=button onclick="simpleControl.ThemedBackgroundColor=colorName.value">
</body>
</html>

SimpleControl.cs

using System;
using System.Drawing;
using System.Windows.Forms;

public class SimpleControl : Control {
  public SimpleControl() {
   this.BackColor = Color.Green;
  }

  public void SayHello() {
    MessageBox.Show("Hello from Windows Forms");
  }

  public string ThemedBackgroundColor {
    get { return ColorTranslator.ToHtml(this.BackColor); }
    set { this.BackColor = ColorTranslator.FromHtml(value); }
  }
}

 

Notice now that after you deploy this control, you can click on the link "Say Hello" to cause a Windows Forms MessageBox to appear, and that entering an HTML color into the text box and clicking the button next to it changes the color of the managed control

Published Wednesday, January 25, 2006 2:27 PM by AndrewDownum
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker