本文最后更新于 2024-11-11,文章可能存在过时内容,如有过时内容欢迎留言或者联系我进行反馈。
前言 {#%E5%89%8D%E8%A8%80}
在WPF中使用WebView2 时,发现无法在触摸屏中对WebView2 打开的网页进行滑动操作,经过研究发现,WPF内置的触笔和触摸支持与WebView2中的触笔和触摸存在冲突,需要禁用掉WPF内置的触笔和触摸支持才能解决。
解决方案 {#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88}
方法一 {#%E6%96%B9%E6%B3%95%E4%B8%80}
使用AppContextSwitchOverrides禁用WPF内置的触笔和触摸支持
在你的应用程序的app.config
文件中添加以下配置,可以关闭WPF内置的实时触摸(RealTimeStylus)支持,从而改用Windows触摸消息(WM_TOUCH
):
<configuration>
<runtime>
<AppContextSwitchOverrides value="Switch.System.Windows.Input.Stylus.DisableStylusAndTouchSupport=true" />
</runtime>
</configuration>
方法二 {#%E6%96%B9%E6%B3%95%E4%BA%8C}
使用反射禁用WPF的RealTimeStylus
public static void DisableWPFTabletSupport()
{
// Get a collection of the tablet devices for this window.
TabletDeviceCollection devices = System.Windows.Input.Tablet.TabletDevices;
if (devices.Count > 0)
{
// Get the Type of InputManager.
Type inputManagerType = typeof(System.Windows.Input.InputManager);
// Call the StylusLogic method on the InputManager.Current instance.
object stylusLogic = inputManagerType.InvokeMember("StylusLogic", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, InputManager.Current, null);
if (stylusLogic != null)
{
// Get the type of the stylusLogic returned from the call to StylusLogic.
Type stylusLogicType = stylusLogic.GetType();
// Loop until there are no more devices to remove.
while (devices.Count > 0)
{
// Remove the first tablet device in the devices collection.
stylusLogicType.InvokeMember("OnTabletRemoved", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic, null, stylusLogic, new object[] { (uint)0 });
}
}
}
}
注意 {#%E6%B3%A8%E6%84%8F}
如果你的WPF程序中还包含了其他的需要滑动操作的控件,如果禁用了WPF内置的触笔输入会导致其他控件无法进行滑动操作,此方案仅适用于WPF程序中只有WebView2一个需要滑动操作的控件。