root/Apple Wireless Keyboard Helper/trunk/Misuzilla.Applications.AppleWirelessKeyboardHelper/Program.cs

Revision 350, 8.7 kB (checked in by tomoyo, 14 months ago)

KeyUp? イベントを作った。

  • Property svn:keywords set to Id
Line 
1using System;
2using System.Diagnostics;
3using System.IO;
4using System.Reflection;
5using System.Text;
6using System.Windows.Forms;
7using IronPython;
8using Microsoft.Scripting;
9using Microsoft.Scripting.Hosting;
10
11namespace Misuzilla.Applications.AppleWirelessKeyboardHelper
12{
13    public class Program
14    {
15        private static NotifyIcon _notifyIcon;
16        private const String ApplicationName = "Apple Wireless Keyboard Helper";
17        private static IScriptModule _module;
18
19        public static Int32 BalloonTipTimeout = 1500;
20
21        private const UInt32 JISAlphaNumericKeyScanCode = 113; // 113
22        private const UInt32 JISKanaKeyScanCode = 114; // 114
23       
24        //[STAThread]
25        static void Main()
26        {
27            using (Helper helper = new Helper())
28            {
29                // TypeLib �� IDispatch ��悷��                ((PythonEngineOptions)(Script.GetEngine("py").Options)).PreferComDispatchOverTypeInfo = true;
30
31                helper.FnKeyCombinationDown += delegate(Object sender, AppleKeyboardEventArgs e)
32                {
33                    StringBuilder funcName = new StringBuilder("OnDown");
34                    if (e.AppleKeyState == AppleKeyboardKeys.Fn)
35                        funcName.Append("_Fn");
36                    if (e.AppleKeyState == AppleKeyboardKeys.Eject)
37                        funcName.Append("_Eject");
38
39                    funcName.Append("_").Append(e.Key.ToString());
40
41                    Call(funcName.ToString(), e);
42
43                    e.Handled = true;
44                };
45
46                helper.KeyUp += delegate(Object sender, AppleKeyboardEventArgs e)
47                {
48                    if (e.KeyEventStruct.wScan != JISAlphaNumericKeyScanCode && e.KeyEventStruct.wScan != JISKanaKeyScanCode)
49                        return;
50                   
51                    StringBuilder funcName = new StringBuilder("OnUp");
52                    if (e.AppleKeyState == AppleKeyboardKeys.Fn)
53                        funcName.Append("_Fn");
54                    if (e.AppleKeyState == AppleKeyboardKeys.Eject)
55                        funcName.Append("_Eject");
56
57                    funcName.Append("_").Append((e.KeyEventStruct.wScan == JISAlphaNumericKeyScanCode) ? "JISAlphaNumeric" : "JISKana");
58
59                    Call(funcName.ToString(), e);
60
61                    e.Handled = true;
62                };
63
64                helper.SpecialKeyDown += delegate(Object sender, KeyEventArgs e)
65                {
66                    StringBuilder funcName = new StringBuilder("OnDown");
67                    if (e.AppleKeyboardKey == AppleKeyboardKeys.Fn)
68                        funcName.Append("_Fn");
69                    if (e.AppleKeyboardKey == AppleKeyboardKeys.Eject)
70                        funcName.Append("_Eject");
71                    if (e.IsPowerButtonDown)
72                        funcName.Append("_Power");
73
74                    Call(funcName.ToString(), e);
75                };
76
77                helper.Disconnected += delegate
78                {
79                    ShowBalloonTip(Resources.Strings.KeyboardDisconnected, ToolTipIcon.Warning);
80                    helper.Shutdown();
81                    while (!helper.Start())
82                    {
83                        // retry at interval of 10sec
84                        System.Threading.Thread.Sleep(10000);
85                    }
86                    ShowBalloonTip(Resources.Strings.KeyboardConnected, ToolTipIcon.Info);
87                };
88
89                if (!helper.Start())
90                {
91                    MessageBox.Show(Resources.Strings.KeyboardNotConnected, ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
92                    return;
93                }
94
95                helper.Hook();
96
97                SetupNotifyIcon();
98                LoadScripts();
99
100                Application.Run();
101
102                _notifyIcon.Visible = false;
103            }
104        }
105
106        /// <summary>
107        ///
108        /// </summary>
109        /// <param name="funcName"></param>
110        /// <param name="e"></param>
111        private static void Call(String funcName, EventArgs e)
112        {
113            Object funcObj;
114            if (!_module.TryLookupVariable(funcName, out funcObj))
115                return;
116           
117            FastCallable f = funcObj as FastCallable;
118            if (f == null)
119                return;
120            try
121            {
122                f.Call(InvariantContext.CodeContext);
123            }
124            catch (Exception ex)
125            {
126                MessageBox.Show(ex.ToString(), ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
127            }
128        }
129
130
131       
132        /// <summary>
133        ///
134        /// </summary>
135        private static void LoadScripts()
136        {
137            // �Â�����ׂč폜
138            OnUnload(EventArgs.Empty);
139            Unload = null;
140            Load = null;
141
142#pragma warning disable 0618
143            DynamicHelpers.TopNamespace.LoadAssembly(Assembly.GetExecutingAssembly());
144            DynamicHelpers.TopNamespace.LoadAssembly(Assembly.LoadWithPartialName("System.Windows.Forms"));
145#pragma warning restore 0618
146
147            IScriptEnvironment scriptEnv = ScriptEnvironment.GetEnvironment();
148            _module = scriptEnv.CreateModule("ScriptModule");
149
150            Boolean hasScripts = false;
151            if (Directory.Exists("Scripts"))
152            {
153                foreach (String path in Directory.GetFiles("Scripts", "*.py"))
154                {
155                    Debug.WriteLine("Load Script: " + path);
156                    try
157                    {
158                        IScriptEngine engine = scriptEnv.GetLanguageProviderByFileExtension(Path.GetExtension(path)).GetEngine();
159                        engine.ExecuteFileContent(path, _module);
160                        hasScripts = true;
161                    }
162                    catch (SyntaxErrorException se)
163                    {
164                        MessageBox.Show(String.Format(Resources.Strings.ScriptSyntaxException, path, se.Line, se.Column, se.Message), ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
165                    }
166                    catch (Exception e)
167                    {
168                        MessageBox.Show(String.Format(Resources.Strings.ScriptException, path, e.Message), ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
169                    }
170                }
171            }
172
173            // �����ݍ�����Ȃ�������t�H���g
174            if (!hasScripts)
175            {
176                Script.GetEngine("py").Execute(Resources.Strings.DefaultPythonScript, _module);
177            }
178
179            // ��s
180            _module.Execute();
181           
182            OnLoad(EventArgs.Empty);
183           
184            ShowBalloonTip(Resources.Strings.ScriptsLoaded, ToolTipIcon.Info);
185        }
186
187        /// <summary>
188        ///
189        /// </summary>
190        private static void SetupNotifyIcon()
191        {
192            _notifyIcon = new NotifyIcon();
193            _notifyIcon.Icon = Resources.Common.AppleWirelessKeyboardHelperTrayIcon16x16;
194            _notifyIcon.Text = ApplicationName;
195            _notifyIcon.Visible = true;
196            _notifyIcon.ContextMenu = new ContextMenu(new MenuItem[]{
197                new MenuItem(Resources.Strings.MenuItemReloadScripts, delegate {
198                    LoadScripts();
199                })
200                , new MenuItem("-")
201                , new MenuItem(Resources.Strings.MenuItemExit, delegate {
202                    Application.Exit();
203                })
204            });
205        }
206
207        public static void ShowBalloonTip(String text)
208        {
209            ShowBalloonTip(text, ToolTipIcon.Info);
210        }
211       
212        public static void ShowBalloonTip(String text, ToolTipIcon toolTipIcon)
213        {
214            _notifyIcon.ShowBalloonTip(BalloonTipTimeout, ApplicationName, text, toolTipIcon);
215        }
216
217        public static event EventHandler Unload;
218        private static void OnUnload(EventArgs e)
219        {
220            try
221            {
222                if (Unload != null)
223                    Unload(new Object(), e);
224            }
225            catch (Exception ex)
226            {
227                Debug.WriteLine(ex.ToString());
228            }
229        }
230        public static event EventHandler Load;
231        private static void OnLoad(EventArgs e)
232        {
233            try
234            {
235                if (Load != null)
236                    Load(new Object(), e);
237            }
238            catch (Exception ex)
239            {
240                Debug.WriteLine(ex.ToString());
241            }
242        }
243    }
244}
Note: See TracBrowser for help on using the browser.