posts - 66, comments - 34, trackbacks - 0, articles - 1
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

让SendKeys支持空格键

Posted on 2008-03-13 15:26 God Blue Shadow 阅读(102) 评论(0)  编辑 收藏 所属分类: 个人技术文章

  SendKeys模拟键盘的操作,设置一定的键值,便可以自动控制。但是我们在使用的过程中,发现SendKeys不支持空格键,在很多的应用场景,都需要使用空格键,所以只好通过反射的方式将其调整。
代码如下:

            Type typeForKeywords = Type.GetType("System.Windows.Forms.SendKeys+KeywordVk[], System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");


            Type typeForKeywordItem = Type.GetType("System.Windows.Forms.SendKeys+KeywordVk, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
            object objNewKey = Activator.CreateInstance(typeForKeywordItem, "SPACE", 0x20);

            Type typeForSendKeys = typeof(SendKeys);

            FieldInfo fieldForkeywords = typeForSendKeys.GetField("keywords", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Static);
            object objKeys = fieldForkeywords.GetValue(null);


            Type typeForlistForKeyword = Type.GetType("System.Collections.Generic.List`1[[System.Windows.Forms.SendKeys+KeywordVk, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
            object objForTmpKeyWords = Activator.CreateInstance(typeForlistForKeyword);

            MethodInfo mi = typeForlistForKeyword.GetMethod("Add");

            foreach (object var in (Array)objKeys)
            {
                //list.Add(var);
                mi.Invoke(objForTmpKeyWords, new object[] { var });
            }

            //list.Add(key);
            mi.Invoke(objForTmpKeyWords, new object[] { objNewKey });

            mi = typeForlistForKeyword.GetMethod("ToArray");
            object objArray = mi.Invoke(objForTmpKeyWords, null);
            fieldForkeywords.SetValue(null, objArray);


标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交