c# - WPF : emulate real input device? 中的虚拟键盘

标签 c# wpf button keyboard keyevent

我想在win7中创建一个简单的虚拟键盘

|---|---|---| 9 char in first block ( abcdefgijk) 

|---|---|---|

|---|---|---|

have 9 button, when click first button change to another view.

|---|---|---|
 a     b  c   
|---|---|---|
 e    f   g    
|---|---|---|
 i    j  k 

Now I am confused about how to click a button like press keyboard can generate char output to another application. I am using

System.Windows.Forms.SendKeys.SendWait(sendString);

但它不起作用。我知道 sendString 是正确的,因为我认为它像 Console.WriteLine(sendString);

另一个问题是点击按钮时焦点不会变回按钮。

有人知道如何实现此键盘的解决方案吗?

谢谢!

感谢您的回复,实际上我已经添加了这些代码 当我多次点击按钮时它也有一些问题。当我单击按钮时,焦点也无法工作,它总是聚焦在按钮上。在此示例中,它仅包含 2 个按钮。你能帮忙看看那些代码发现错误吗?许多人认为!!

namespace WpfApplication5
{
    public partial class UserControl1 : UserControl
    {
        [DllImport("user32.dll")]
        public static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex);

        private IInputElement focusedInputElement;
        private Window parentWindow;
        private List<Button> keyCollection = new List<Button>();

        public UserControl1(Window parent)
        {
           this.parentWindow = parent;
           this.setupKeyboardControl();
        }

        public UserControl1(IInputElement elementToFocusOn)
        {
            // set focus
            this.focusedInputElement = elementToFocusOn;
            // setup this control
            this.setupKeyboardControl();
        }

        private void setupKeyboardControl()
        {
            InitializeComponent();
            // add all keys to internal collection
            this.addAllKeysToInternalCollection();
            // install clicks
            this.installAllClickEventsForCollection(this.keyCollection);
        }

        private void addAllKeysToInternalCollection()
        {
            // itterate all panels
            // itterate all buttons
            // add to list
            Console.WriteLine("Run at here"); 
            this.keyCollection.Add(A);
            this.keyCollection.Add(B);
        }

        /// <summary>
        /// Install click events for all keys in a collection
        /// </summary>
        /// <param name="keysToInstall"></param>
        private void installAllClickEventsForCollection(List<Button> keysToInstall)
        {
            // itterate all
            foreach (Button buttonElement in keysToInstall)
            {
                // install click event
                buttonElement.Click += new RoutedEventHandler(buttonElement_Click);
            }
        }

        /* private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.A)
               A.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            else if (e.Key == Key.B)
               B.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
        }*/

        void buttonElement_Click(object sender, RoutedEventArgs e)
        {
            // create variable for holding string
            String sendString = "";

            try
            {
                // stop all event handling
                e.Handled = true;

                // set sendstring to key
                sendString = ((Button)sender).CommandParameter.ToString();

                // if something to send
                if (!String.IsNullOrEmpty(sendString))
                {
                    // if sending a string
                    if (sendString.Length > 1)
                    {
                        // add {}
                        sendString = "{" + sendString + "}";
                    }

                    // if a focusable element has been specified
                    if (this.focusedInputElement != null)
                    {
                        Console.WriteLine("1",sendString);
                        // set keyboard focus
                        Keyboard.Focus(this.focusedInputElement);
                        // set normal focus
                        this.focusedInputElement.Focus();
                    }

                    // send key to simulate key press
                   // System.Windows.Forms.SendKeys.Send(sendString);

                   System.Windows.Forms.SendKeys.SendWait(sendString);
                    Console.WriteLine(sendString);

                }
            }
            catch (Exception)
            {
                // do nothing - not important for now
                Console.WriteLine("Could not send key press: {0}", sendString);
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            // if we have specified a parent
            if (this.parentWindow != null)
            {
                // Get this window's handle
                IntPtr HWND = new WindowInteropHelper(this.parentWindow).Handle;
                Console.WriteLine("Run in UserControl load");
                // style of window?
                int GWL_EXSTYLE = (-20);
                // get - retrieves information about a specified window
                GetWindowLong(HWND, GWL_EXSTYLE);
                // set - changes the attribute of a specified window - I think this stops it being focused on
                SetWindowLong(HWND, GWL_EXSTYLE, (IntPtr)(0x8000000));
            }
        }
    }
}

最佳答案

最可靠的方法是使用 Win32 API

[DllImport("user32.dll")]
public static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

[DllImport("user32.dll", EntryPoint = "SendInput")]
public static extern uint SendInput(uint nInputs, InputKeys[] inputs, int cbSize);

有一个很好的示例,说明您希望通过 CodePlex 上的工作应用程序完成什么

http://wosk.codeplex.com/

关于c# - WPF : emulate real input device? 中的虚拟键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10117034/

相关文章:

swift - 我如何知道最后按下了哪个按钮 - SWIFT?

c# - 通用父集合拆分为子集合

c# - 如何从 COM 客户端访问基于列表(Of T)的对象

c# - 登录网站并检索数据

c# - 如何通过拖动扩展窗口框架使 WPF 窗口可移动?

android - 使单个按钮宽度以编程方式填充父级

c# - 有没有办法在其内部重建一个对象?

javascript - 如何使一个部分占据 Dynamics CRM 表单编辑器中的整个空间

c# - MVVM WPF Multibinding 不适用于命令参数

ios - 如何从 IOS 应用程序中按下的按钮发送 URL 字符串/Web 请求