Tuesday, January 20, 2009

Using Notify Icon in Visual Basic 2005


To add notify icon to system tray is much easier in VB2005 than VB6. Create a new Windows Application in VB2005. Add NotifyIcon control as shown in the following figure.


Select "NotifyIcon1" control. In its properties window, choose "Icon" and open your icon to be used. If you do not define an icon there, you will not see notify icon in the system tray.
To display the notify icon when you close your application, go to code view and enter the following code to FormClosing event.

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing        
          If MessageBox.Show("Do you really want to exit?", "Exit", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then            
                e.Cancel = True           
                Me.Visible = False
                NotifyIcon1.Visible = True
          End If        
    End Sub 

To display the application back when you double click the notify icon in the system tray, write the following code in MouseDoubleClick event of NotifyIcon1 control.

Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
          Me.Visible = True ' Show the form.
          Me.Activate() ' Activate the form.
          NotifyIcon1.Visible = False
End Sub

To close the application also from File menu and context menu. Add these controls.


Then add the code 'Me.Close()' to their click event so that it becomes ...

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
          ' Close the form, which closes the application.
          Me.Close()
End Sub

Private Sub ContextMenuStrip1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ContextMenuStrip1.Click
          Me.Close()
End Sub

Select NotifyIcon1 control and define the ContextMenuStrip1 control in its ContestMenuStrip property so that the pop up menu will appear when you right click on the notify icon.

After that you can run the program. When you close the window, a message box will appear to confirm that you really want to exit. If you choose "No", the application will remain in the system tray on which you can double click to call back the application.

Sunday, January 18, 2009

Capturing and Sending Key -Using AJAX

AJAX is not a new programming language, but a technique for creating better, faster, and more interactive web applications. By using the key object -XMLHttpRequest of AJAX, we can create a dynamic webpage which can make a request and get a response from web server in the background without reloading the page. The user may not even notice that it is communicating invisibly.
Let us discuss an example that captures and sends the key input using AJAX. This example is based on the one that can be found in W3Schools site. There will be three files- keyCapture.html, keyCapture.js, and keyCapture.php.
First, we will create an HTML page called "keyCapture.html" that have a DIV element to display the message returned by the server. All JavaScript will be put in a separate file.


<html>
<head>
<title>Key Capture</title>
<script src='keyCapture.js'></script>
</head>
<body>
<form>
Press a key to send to server.
<div id='text1' style="font-size: 40px; color:blue;">
</div>
</form>
</body>
</html>

Second, the JavaScript file called "keyCapture.js" is created to capture keyboard input and send to the server using AJAX. It is explained in details.

var xmlHttp;
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event) {
    var keyChar;
    if (document.all) {
        keyChar = String.fromCharCode(event.keyCode);
    }
    else if (document.getElementById) {
        keyChar = String.fromCharCode(key_event.which);
    }
    else if (document.layers) {
        keyChar = String.fromCharCode(key_event.which);
    }
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        alert("Your Browser does not support AJAX!");
        return;
    }
    var url = "keyCapture.php";
    url = url + "?keyC=" + keyChar + "&sid=" + Math.random();
    xmlHttp.onreadystatechange = stateChanged;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

function stateChanged() { if (xmlHttp.readyState == 4) { document.getElementById('text1').innerHTML = xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }

There are three main parts in this JavaScript file.
1. Creating XMLHttpRequest object
2. To define a function to handle the data returned by the server
3. To send off a request to the server


1. Creating XMLHttpRequest object
Depending on browser, the method for creating XMLHttpRequest object can be different. ActiveXObject is used in Internet Explorer and XMLHttpRequest JavaScript object is used in other browsers. The following JavaScript function can be used to deal with different browsers.
function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

In the function that wants to use the XMLHttpRequest object, we can just call this GetXmlHttpObject() function as
var xmlHttp
xmlHttp=GetXmlHttpObject();


If the object cannot be created, we can alert a message that AJAX is not supported.

if (xmlHttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } 

2. To define a function to handle the data returned by the server
The following JavaScript define a function that will be called when the server response status has changed. The readyState property has five possible values (from 0 to 4) and it checks for request complete state (state value 4) before it process the response.


function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}

When the server response status has changed, the function stored in onreadystatechange property will be called automatically. It must be defined in the function that initiates the XMLHttpRequest as

xmlHttp.onreadystatechange=stateChanged;


3. To send off a request to the server
When we submit a request using "GET" method, the ids of the fields and values of that fields are sent in the url e.g.,
http://youraddress.com/keyCapture.php?id1=val1
We will modify the url of our php script using that format and add another ramdom value to make sure that cached version is not returned.


var url = "keyCapture.php";
url = url + "?keyC=" + keyChar + "&sid=" + Math.random();

By using the open() method and the send() method of the XMLHttpRequest object, a request can be sent to the server. The first argument of the open method can be GET or POST. The second argument is URL of the server-side script and third one specifies to handle the request asynchronously.

xmlHttp.open("GET", url, true);
xmlHttp.send(null);


Third, the server side script called "keyCapture.php" will be written in PHP as follow.

<?php
//get the parameter from URL
$k=$_GET["keyC"];
echo "Received: " . $k;
?>

Saturday, January 17, 2009

Capture Key Event in JavaScript

A friend of me wanted to control a hardware module that attached to a remote linux server using keyboard input in a client web page. She asked me how to do it. And I also didn't know :) We agreed to use JavaScript in client side and PHP on remote server. In the internet browser of the client computer, she didn't want to fill in and submit a form manually. That means key inputs must be captured directly and immediately sent to remote server to control the hardware accordingly.
After surfing for a while, a web page was found here about how to capture key inputs in JavaScript. Then we wrote a web page in PHP that sends key input directly. See the code that was written in "key.php".



<html>
<head>
<script language="JavaScript" type = "text/javascript">
<!--
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event)
{
if (document.all) //Checks for IE 4.0 or later
{
document.form1.text1.value = String.fromCharCode(event.keyCode);
}
else if (document.getElementById) //checks for Netscape 6 or later
{
document.form1.text1.value = String.fromCharCode(key_event.which);
}
else if (document.layers) //Checks for Netscape 4
{
document.form1.text1.value = String.fromCharCode(key_event.which);
}
document.form1.submit();
}
//-->
</script>
<title>Capture Key Pressed</title>
</head>
<body>
<div style="display:none">
<form name="form1" action="key.php" method=GET>
<input type = "text" name = "text1">
</form>
</div>
<div style="font-size: 40px; color:blue;">
<?php
echo "Received: ";
echo $_GET["text1"];
?>
</div>
</body>
</html>


In this example, the problem in submitting the captured key is that the whole web page reloads everytime a key is pressed. It can be very slow when the page contains a lot of other contents. The better way is to use AJAX (Asynchronous JavaScript and XML) technique.