I’ve been spending most of my time that past year or so blogging about topics related to web site development. I’m going to switch things up a bit here and talk about my current activity, which is building a .NET WinForm app. There are some interesting things about it. For starters, it’s purpose is to periodically retrieve/scrape some information from a secure web site for the user. This eliminates the need for the user to log into the site during the day to check there statistics. Since I want the app to be started up once and they stay running on the computer, I decided to have the app minimize to the system tray and display alerts (balloons) as things change.
I originally was thinking of using HttpWebRequest and similar .NET classes, but couldn’t get things to work. The complexity is with the web site’s login page and I couldn’t figure out how to correctly post and navigate, so I decided to take a different route. I’ve added a WebBrowser control to my main WinForm. I’m making it non-visible since there’s no reason for the user to see it. The nice thing about it is that I can use the Navigate method to browse to the correct URLs, and then use the Document property to get the page’s HTML. It’s pretty easy to find the various HTML elements, set values into fields, and invoke methods. It’s also easy to extract information.
Here’s a simple example:
HtmlDocument doc = webBrowser1.Document;
if (doc != null)
{
HtmlElement userId = doc.GetElementById("userId");
HtmlElement passWord = doc.GetElementById("passWord");
userId.SetAttribute("value", "myUserId");
passWord.SetAttribute("value", "myPassword");
HtmlElement btn = doc.GetElementById("loginBtn");
btn.InvokeMember("Click");
}
From this example you can see how easy to work with the web page. One thing to understand is that you need to implement the DocumentCompleted event for the web browser control, and that is where you put your code to parse the document. That’s the best way to make sure you don’t try to access the document before it is completely loaded up.
As I mentioned, I want the app to minimize to the system tray. After a little research I found out how easy that is too. In .NET there is a new class- NotifyIcon - that makes it very easy to have the app icon appear in the system tray and display "balloon tips".
Create the NotifyIcon is simple. Add a member to your Winform class and the construct it in your page constructor or load.
private NotifyIcon _ni;
public Form1()
{
InitializeComponent();
_ni = new NotifyIcon();
_ni.Icon = new Icon(GetType(), "TrayIcon.ico");
_ni.Visible = true;
_ni.Text = "Cool Tool";
ContextMenu mnu = new ContextMenu();
mnu.MenuItems.Add(new MenuItem("Options"));
mnu.MenuItems.Add(new MenuItem("About"));
_ni.ContextMenu = mnu;
}
Then, at the appropriate point in your code you can display balloons:
_ni.ShowBalloonTip(2000, "Status", "Some helpful message", ToolTipIcon.None);