簡體   English   中英

使用C#和WPF防止Windows上的屏幕捕獲

[英]Prevent screen capture on Windows with C# and WPF

我試圖阻止我的WPF窗口的截圖,如Microsoft Office。

我嘗試使用SetWindowDisplayAffinity,但它總是返回false,我真的不知道在哪里調用這個方法。

App.xaml中:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetWindowDisplayAffinity(IntPtr hwnd, DisplayAffinity affinity);

protected override void OnStartup(StartupEventArgs e)
{
    var mainView = new MainWindow();
    var ok = SetWindowDisplayAffinity(Process.GetCurrentProcess().MainWindowHandle, DisplayAffinity.Monitor);
    mainView.Show();
}

但SetWindowDisplayAffinity方法始終返回false。 我發現了另一個問題,但沒有說明這個方法應該在哪里。

在主窗口的Loaded事件中添加一個事件處理程序: Loaded="Window_Loaded"

然后定義該方法,如下所示:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    IntPtr handle = (new WindowInteropHelper(this)).Handle;
    bool s = SetWindowDisplayAffinity(handle, DisplayAffinity.Monitor);
    MessageBox.Show(s.ToString());
}

然后它會返回True,並且在截取屏幕時該窗口會變黑。

如果在InitializeComponent();之后將相同的代碼放在構造函數中InitializeComponent(); 然后它返回False並且窗口沒有變黑。

注意(new WindowInteropHelper(this)).Handle如果沒有加載窗口, (new WindowInteropHelper(this)).Handle將等於0並且在加載窗口后它將具有一個值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM