Chinaunix首页 | 论坛 | 博客
  • 博客访问: 406852
  • 博文数量: 51
  • 博客积分: 2030
  • 博客等级: 大尉
  • 技术积分: 1109
  • 用 户 组: 普通用户
  • 注册时间: 2007-04-15 08:11
文章分类

全部博文(51)

文章存档

2022年(1)

2016年(2)

2015年(1)

2014年(2)

2013年(4)

2011年(9)

2010年(2)

2009年(5)

2008年(14)

2007年(11)

我的朋友

分类: Windows平台

2016-03-23 11:25:30

    最近要使用软键盘,自己用VC写要花些时间,所以就用系统自带的吧。但用C#每次调用软键盘时位置总是不固定的,所以就查了网上一些做过朋友的博客,发现位置有时可以固定,有时不可以固定。最后摸索了很久终于把问题解决了。现在把daemo代码贴出来,方便以后使用的网友吧。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;


namespace SetOskeyPostion
{
    public partial class Form1 : Form
    {
       // 申明要使用的dll和api
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        public extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
       [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "MoveWindow")]
       public static extern bool MoveWindow(System.IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);


        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);


        private System.Diagnostics.Process softKey; 
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            //打开软键盘
            try
            {
                if (!System.IO.File.Exists(Environment.SystemDirectory + "\\osk.exe"))
                {
                    MessageBox.Show("软件盘可执行文件不存在!");
                    return;
                }


                softKey = System.Diagnostics.Process.Start("C:\\Windows\\System32\\osk.exe");
                // 上面的语句在打开软键盘后,系统还没用立刻把软键盘的窗口创建出来了。所以下面的代码用循环来查询窗口是否创建,只有创建了窗口
               // FindWindow才能找到窗口句柄,才可以移动窗口的位置和设置窗口的大小。这里是关键。
                IntPtr intptr = IntPtr.Zero;
                while (IntPtr.Zero == intptr)
                {
                    System.Threading.Thread.Sleep(100);
                    intptr = FindWindow(null, "屏幕键盘");
                }


                // 获取屏幕尺寸
                int iActulaWidth = Screen.PrimaryScreen.Bounds.Width;
                int iActulaHeight = Screen.PrimaryScreen.Bounds.Height;


                // 设置软键盘的显示位置,底部居中
                int posX = (iActulaWidth - 1000) / 2;
                int posY = (iActulaHeight - 300);


                //设定键盘显示位置
                MoveWindow(intptr, posX, posY, 1000, 300, true);


                //设置软键盘到前端显示
                SetForegroundWindow(intptr);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

阅读(20415) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

wzc12023-03-31 10:44:12

mengda:为什么我直接报错说软件盘可执行文件不存在呢

您好请问您解决这个问题了吗

回复 | 举报

mengda2019-12-04 11:26:54

为什么我直接报错说软件盘可执行文件不存在呢