代码如下:
/// <summary> /// 按钮设置快捷键 /// </summary> /// <param name="pageCurrent">Page</param> /// <param name="slkey"></param> private void SetShortcutKey(System.Web.UI.Page pageCurrent, SortedList slkey) { int icount = slkey.Count; string strjavascript = "<script type=\"text/javascript\"> " + "document.onkeydown = function() " + "{" + " if(event.keyCode==" + slkey.GetByIndex(0) + ")" + " { " + " document.getElementById('" + slkey.GetKey(0) + "').click();" + " }"; for (int j = 1; j < icount; j++) { strjavascript += "if(event.keyCode==" + slkey.GetByIndex(j) + ")" + " { " + " document.getElementById('" + slkey.GetKey(j) + "').click();" + " }"; } strjavascript += "}</script>"; pageCurrent.ClientScript.RegisterStartupScript(pageCurrent.GetType(), Guid.NewGuid().ToString(), strjavascript); }
SortedList _shortcutkeys; public void AddShortcutKey(WebControl control, string keycode) { if (_shortcutkeys == null) { _shortcutkeys = new SortedList(); } _shortcutkeys.Add(control.ClientID, keycode); } /// <summary> /// 设置快捷键 /// </summary> private void ShortcutKey() { AddShortcutKey(btnSave, ShortKeyConst.F7); AddShortcutKey(btnSubmit, ShortKeyConst.F12); } /// <summary> /// 设置快捷键 /// </summary> /// <param name="writer"></param> protected override void Render(HtmlTextWriter writer) { if (_shortcutkeys != null) { SetShortcutKey(this, _shortcutkeys); } base.Render(writer); } public class ShortKeyConst { public const string F2 = "113"; public const string F7 = "118"; public const string F8 = "119"; public const string F9 = "120"; public const string F11 = "122"; public const string F12 = "123"; public const string Esc = "27"; }