|
Catching F1 KeyPress to Display Web Based Help |
|
I was investigating the possibility of catching the f1 key for displaying additional popup help in a web page... I eventually abandoned the idea, but have some useful information as a result. The real issue at hand, is that the event handler only fires when the form has focus; and both IE and Firefox have browser help that fires off the F1 key, which could be confusing for users looking at general help when they wanted help with your web page.
Here is the code I was using to test.
protected override void OnPreRender(EventArgs e)
{
Page.RegisterStartupScript("f1helper",F1ForHelp());
}
protected string F1ForHelp ()
{
StringBuilder s = new StringBuilder();
s.Append(@"<script language=""JavaScript"" type=""text/javascript""><!--");
s.Append("\n");
s.Append(@"document.onkeydown = keyhandler;");
s.Append("\n");
s.Append(@"function keyhandler(e) {");
s.Append("\n");
s.Append(@" var Key = (window.event) ? event.keyCode : e.keyCode;");
s.Append("\n");
s.Append(@" if (Key != 0)");
s.Append("\n");
s.Append(@" alert('Key pressed! ASCII-value: ' + Key);");
s.Append("\n");
s.Append(@" if (Key == 112)");
s.Append("\n");
s.Append(@" alert('Help!');return false;");
s.Append("\n");
s.Append(@"event.returnValue=false;");
s.Append("\n");
s.Append(@"event.cancel = true;");
s.Append("\n");
s.Append(@"}");
s.Append("\n");
s.Append(@"document.onhelp = function() {alert('help!');return false;};");
s.Append("\n");
s.Append(@"//--></script>");
s.Append("\n");
return s.ToString();
}
Which outputs a javascript block in the page something like
<a language="" title="See JavaScript on Technorati" rel="tag"
href="http://technorati.com/tag/JavaScript" class="tag">JavaScript</a>"" type=""text/javascript""><!--
document.<a title="See onkeydown on Technorati" rel="tag" href="http://technorati.com/tag/onkeydown"
// class="tag">onkeydown</a> = keyhandler;
function keyhandler(e) {
var Key = (window.event) ? event.keyCode : e.keyCode;
if (Key != 0)
alert('Key pressed! ASCII-value: ' + Key);
if (Key == 112)
alert('Help!');return false;
event.returnValue=false;
event.cancel = true;
}
document.<a title="See onhelp on Technorati" rel="tag" href="http://technorati.com/tag/onhelp"
// class="tag">onhelp</a> = function() {alert('help!');return false;};
//--></script>
Notes: Neither IE or Firefox would respond to the onkeypress for the F1 key (ASCII 112) but IE did respond appropriately to the document.onhelp, when my page was active, I was able to trap the F1 key and cancel the browsers own Help Popup... In both IE and Firefox the onkeydown event would fire before the browsers help popup, but I could not trap the Firefox help window from opening when the key was released (not sure exactly what event they are using in order to trap and cancel it).
Maybe this will help someone out there; in the end, I am not sure keyboard shortcuts are such a great idea in such a mouse based environment
Dan