附加属性的使用-调用虚拟键盘
程序员文章站
2022-06-08 22:17:21
...
在之前介绍过附加属性,但是附加属性该怎么样使用呢?这篇文章对上篇文章介绍的虚拟键盘进行一个封装。使它可以用在任意一个支持输入的控件上。
下面直接上代码(我们可以将这个附加属性,新放到一个文件中,
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace VirtualKeyboard
{
public class GetVirtualKeyboardHelper
{
protected GetVirtualKeyboardHelper()
{
////do nothing
}
public static bool GetVirtualKeyboard(DependencyObject obj)
{
return (bool)obj.GetValue(VirtualKeyboardProperty);
}
public static void SetVirtualKeyboard(DependencyObject obj, bool value)
{
obj.SetValue(VirtualKeyboardProperty, value);
}
// Using a DependencyProperty as the backing store for VirtualKeyboard. This enables animation, styling, binding, etc...
public static readonly DependencyProperty VirtualKeyboardProperty =
DependencyProperty.RegisterAttached("VirtualKeyboard", typeof(bool), typeof(GetVirtualKeyboardHelper), new PropertyMetadata(false, OnPropertyChanged));
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var element = d as UIElement;
if (element != null)
{
//触摸时触发
element.TouchDown += ElementTouchDown;
element.LostFocus += ElementLostFocus;
}
}
private static void ElementTouchDown(object sender, RoutedEventArgs e)
{
try
{
StringBuilder sb = new StringBuilder();
string path = "\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe";
var file = Environment.GetEnvironmentVariable("SystemRoot");
var s = file.Split('\\');
for (int i = 0; i < s.Length - 1; i++)
{
sb.Append(s[i]);
}
sb.Append(path);
if (!System.IO.File.Exists(sb.ToString()))
return;
Process.Start(sb.ToString());
}
catch (Exception)
{
//nothing
}
}
private const Int32 WM_SYSCOMMAND = 274;
private const UInt32 SC_CLOSE = 61536;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool PostMessage(IntPtr hWnd, int Msg, uint wParam, uint lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
private static void ElementLostFocus(object sender, RoutedEventArgs e)
{
IntPtr touchhWnd = IntPtr.Zero;
touchhWnd = FindWindow("IPTip_Main_Window", null);
if (touchhWnd == IntPtr.Zero)
return;
PostMessage(touchhWnd, WM_SYSCOMMAND, SC_CLOSE, 0);
}
}
}
那么这个附加属性该怎么使用呢?还是直接上代码
<TextBox Margin="5,5,5,5" Name="textBox" local:GetVirtualKeyboardHelper.VirtualKeyboard="True" ></TextBox>
此时当我们点击这个textBox就会调用处虚拟键盘
本文标题:附加属性的使用-调用虚拟键盘
文章作者:huangruifeng
发布时间:2017年11月29日 - 17:11
最后更新:2017年11月29日 - 17:11
原始链接
许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。