<Window x:Class="SfwTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Set Foreground Window Test" Width="525"
SizeToContent="Height"
Background="{x:Static SystemColors.ControlBrush}">
<StackPanel>
<Label>Указатель этого окна:</Label>
<TextBox x:Name="MyHandle" IsReadOnly="True" />
<Label>Указатель другого окна:</Label>
<TextBox x:Name="AnotherHandle" />
<Button x:Name="Go" Click="Go_Click">Set Foreground Window</Button>
</StackPanel>
</Window>
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace SfwTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += (sender, args) =>
{
var myHandle = (int)new WindowInteropHelper(this).Handle;
MyHandle.Text = myHandle.ToString();
};
}
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
private void Go_Click(object sender, RoutedEventArgs e)
{
try
{
var text = AnotherHandle.Text.Trim();
if (String.IsNullOrEmpty(text))
throw new ArgumentNullException("Указатель другого окна");
var anotherHandle = (IntPtr)int.Parse(text);
SetForegroundWindow(anotherHandle);
}
catch (Exception ex)
{
AnotherHandle.Focus();
MessageBox.Show(this, ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}