找了很久
<Window x:Class="TestWebbowser.TestMaskWind" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Background="WhiteSmoke" Title="MainWindow" Height="1277" Width="947" MouseMove="canvas_MouseMove" MouseDown="Window_MouseDown" MouseUp="Window_MouseUp"> <Grid Height="1024" Width="800"> <Grid.Background> <ImageBrush ImageSource="s.jpg" /> </Grid.Background> <Rectangle Height="100" HorizontalAlignment="Left" Margin="164,22,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="Lime" /> <Button Content="Button" Height="83" HorizontalAlignment="Left" Margin="526,109,0,0" Name="button1" VerticalAlignment="Top" Width="115" Click="button1_Click" /> <Grid x:Name="grid" Background="#E54E4E4E" Opacity="1" ></Grid> </Grid> </Window>
后台代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace TestWebbowser { /// <summary> /// Interaction logic for TestMaskWind.xaml /// </summary> public partial class TestMaskWind : Window { public TestMaskWind() { InitializeComponent(); RectangleGeometry rg = new RectangleGeometry(); rg.Rect = new Rect(0, 0, this.Width, this.Height); gridGeometry = Geometry.Combine(gridGeometry, rg, GeometryCombineMode.Union, null); grid.Clip = gridGeometry; } private bool isDown = false; PathGeometry gridGeometry = new PathGeometry(); private void canvas_MouseMove(object sender, MouseEventArgs e) { if (isDown) { EllipseGeometry rg = new EllipseGeometry(); rg.Center = e.GetPosition(this); rg.RadiusX = 50; rg.RadiusY = 50; //排除几何图形 gridGeometry = Geometry.Combine(gridGeometry, rg, GeometryCombineMode.Exclude, null); grid.Clip = gridGeometry; } } private void button1_Click(object sender, RoutedEventArgs e) { MessageBox.Show("OK!"); } private void Window_MouseDown(object sender, MouseButtonEventArgs e) { // if (e.LeftButton == MouseButtonState.Pressed) // { isDown = true; // } } private void Window_MouseUp(object sender, MouseButtonEventArgs e) { isDown = false; } } }