gpt4 book ai didi

c# - WPF - 没有焦点的滚动

转载 作者:太空狗 更新时间:2023-10-29 22:01:46 25 4
gpt4 key购买 nike

我想在应用程序窗口未获得焦点时滚动 ScrollViewer 控件。我在 Windows 窗体中找到了一些解决方案,但在 WPF 中找不到,因为我需要的一些东西不可用。

也许这里有人可以帮我解决我的问题?

提前致谢。

编辑:

我想在鼠标悬停在 ScrollViewer 上时使用鼠标滚轮滚动 ScrollViewer 控件,但在应用程序窗口未获得焦点时也是如此。

最佳答案

我找到了一个解决方案。这里有一个例子:

XAML

<Window x:Class="Project.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="300" Width="500">
<ScrollViewer x:Name="ScrollViewer">
<StackPanel>
<Border Background="Blue" Width="100" Height="100" />
<Border Background="Red" Width="100" Height="100" />
<Border Background="Blue" Width="100" Height="100" />
<Border Background="Red" Width="100" Height="100" />
<Border Background="Blue" Width="100" Height="100" />
<Border Background="Red" Width="100" Height="100" />
</StackPanel>
</ScrollViewer>
</Window>

代码隐藏

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;

namespace Project
{
public partial class MainWindow : Window
{
private const int WH_MOUSE_LL = 14;
private const int WM_MOUSEWHEEL = 0x020A;
private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);

private IntPtr _handle;

public MainWindow()
{
InitializeComponent();

_handle = new WindowInteropHelper(this).Handle;
SetWindowsHookEx(WH_MOUSE_LL, MouseChanged, _handle, 0);

ScrollViewer.PreviewMouseWheel += ScrollViewer_MouseWheel;
Unloaded += MainWindow_Unloaded;
}

private void MainWindow_Unloaded(object sender, RoutedEventArgs e)
{
UnhookWindowsHookEx(_handle);
}

private void ScrollViewer_MouseWheel(object sender, MouseWheelEventArgs e)
{
e.Handled = true;
}

private IntPtr MouseChanged(int nCode, IntPtr wParam, IntPtr lParam)
{
if (ScrollViewer.IsMouseOver && WM_MOUSEWHEEL == (int)wParam)
{
MouseData mouseData = (MouseData)Marshal.PtrToStructure(lParam, typeof(MouseData));
ScrollViewer.ScrollToVerticalOffset(ScrollViewer.VerticalOffset - mouseData.Z / 200000.0);
}
return CallNextHookEx(_handle, nCode, wParam, lParam);
}

[StructLayout(LayoutKind.Sequential)]
private struct MouseData
{
public int X;
public int Y;
public int Z;
}

[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);

[DllImport("user32.dll")]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);

[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
}
}

关于c# - WPF - 没有焦点的滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5139691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com