我正在编写一个小概念验证,要求我听一些按键组合,当按下时会在当前光标位置下面打开一个小WPF/WinForms
窗口。我更像是一个网络人员,所以我从这开始就遇到了麻烦。
有人能指出我正确的方向吗?或者提供一些资源/示例?
感谢。
答案 0 :(得分:11)
为WPF尝试此示例。按 Enter 键可提前显示Popup
窗口,接收鼠标光标的坐标。
<强> XAML
强>
<Window x:Class="OpenWindowForCursor.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
WindowStartupLocation="CenterScreen"
PreviewKeyDown="Window_PreviewKeyDown">
<Grid>
<Popup Name="PopupWindow"
Placement="Relative"
IsOpen="False"
StaysOpen="False">
<Border Width="100"
Height="100"
Background="AntiqueWhite">
<Label Content="Test" />
</Border>
</Popup>
</Grid>
</Window>
<强> Code-behind
强>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
PopupWindow.IsOpen = true;
var point = Mouse.GetPosition(Application.Current.MainWindow);
PopupWindow.HorizontalOffset = point.X;
PopupWindow.VerticalOffset = point.Y;
}
}
}
<强> Edit: An easier solution
强>
您只需为 Placement="Mouse"
设置Popup
,而不是接收鼠标的坐标:
<强> XAML
强>
<Grid>
<Popup Name="PopupWindow"
Placement="Mouse"
IsOpen="False"
StaysOpen="False">
<Border Width="100"
Height="100"
Background="AntiqueWhite">
<Label Content="Test" />
</Border>
</Popup>
</Grid>
<强> Code-behind
强>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
PopupWindow.IsOpen = true;
}
}
}