2014-03-30 26 views
7

我正在寫一個小概念驗證,要求我聽一些按下組合鍵,當按下這個組合鍵時,會在當前光標位置下方打開一個小的WPF/WinForms窗口。我更像是一個網絡人,所以我從這個開始就遇到了麻煩。在光標位置打開一個小浮動窗口

任何人都可以指向正確的方向嗎?或者提供一些資源/例子?

謝謝。

回答

10

試試WPF的這個例子。通過按輸入鍵提前接收鼠標光標的座標,顯示一個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; 
     } 
    } 
} 
+1

非常感謝你! – JanivZ

相關問題