在媒体播放期间从C#中的WPF应用程序在Windows上启用屏幕保护程序
我是WPF和c的新手。我在一个简单的WPF应用程序中使用MediaElement来播放循环视频,使用情节提要 现在在这个项目中,我遇到了一个大问题。在MediaElement中播放视频会阻止屏幕保护程序启动。但在我的情况下,我需要正常的windows行为。(自动屏幕保护程序和自动注销等。) 即使在我的MediaElement中播放视频,如何使正常的屏幕保护程序再次出现 代码很简单: 主窗口:在媒体播放期间从C#中的WPF应用程序在Windows上启用屏幕保护程序,c#,wpf,windows,mediaelement,screensaver,C#,Wpf,Windows,Mediaelement,Screensaver,我是WPF和c的新手。我在一个简单的WPF应用程序中使用MediaElement来播放循环视频,使用情节提要 现在在这个项目中,我遇到了一个大问题。在MediaElement中播放视频会阻止屏幕保护程序启动。但在我的情况下,我需要正常的windows行为。(自动屏幕保护程序和自动注销等。) 即使在我的MediaElement中播放视频,如何使正常的屏幕保护程序再次出现 代码很简单: 主窗口: <Window x:Name="BrutusView" x:Class="BRUTUS_Panel
<Window x:Name="BrutusView" x:Class="BRUTUS_Panel_View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BRUTUS_Panel_View"
mc:Ignorable="d"
Title="3nb BRUTUS Side Panel Player" Height="320" Width="256" HorizontalAlignment="Center" VerticalAlignment="Center" Left="0" Top="0" Deactivated="BrutusView_Deactivated" LostFocus="BrutusView_LostFocus" Loaded="BrutusView_Loaded" WindowStyle="ToolWindow" ResizeMode="CanResize" Icon="F:\Dokumente\Visual Studio 2015\Projects\BRUTUSConfig\BRUTUSConfig\3nb.ico" Topmost="True" ShowInTaskbar="False" ShowActivated="False" Visibility="Visible">
<Grid>
<MediaElement x:Name="myMediaElement" LoadedBehavior="Manual" HorizontalAlignment="Center" VerticalAlignment="Center" IsMuted="True" Stretch="UniformToFill">
<MediaElement.Triggers>
<EventTrigger RoutedEvent="MediaElement.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<MediaTimeline Source="C:\Animations\1.mp4" Storyboard.TargetName="myMediaElement" RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</MediaElement.Triggers>
</MediaElement>
</Grid>
</Window>
答案包含两种解决方案:(i)基于UWP
DisplayRequest
类,(ii)基于更通用的自定义ScreenSaverManager
类
1。UWPDisplayRequest
class
Windows提供了请求暂停屏幕保护程序的直接方法,并成功调用该方法可确保屏幕保护程序不会因用户不活动而启动,即在媒体播放期间。如果方法再次启用屏幕保护程序,则可能出现相反的情况。这两种方法在Windows 10(UWP运行时)中都可用,可以通过Windows.System.Display.DisplayRequest
class访问。下面是如何在UWP应用程序之外(WPF桌面应用程序中)使用它的示例
在使用代码之前,有必要将以下引用添加到Visual Studio中从模板创建的标准WPF应用程序中:(i)目录中的Windows.winmd
:C:\Program Files(x86)\Windows Kits\10\UnionMetadata
和(ii)System.Runtime.WindowsRuntime.dll
目录:C:\ProgramFiles(x86)\Reference Assembly\Microsoft\Framework\.NETCore\v4.5.1
(或v4.5)
在播放期间暂停或启用屏幕保护程序,将playaback事件的启动和停止挂接到相关方法
using System;
using System.Windows;
using System.Windows.Controls;
using Windows.System.Display;
namespace SuspendScreenSaverWpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private DisplayRequest mDisplayRequest;
public MainWindow()
{
InitializeComponent();
}
private void SuspendButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
try
{
if (mDisplayRequest == null)
{
// This call creates an instance of the displayRequest object
mDisplayRequest = new DisplayRequest();
}
}
catch (Exception ex)
{
this.MessageBoard.Content = $"Error Creating Display Request: {ex.Message}";
}
if (mDisplayRequest != null)
{
try
{
// This call activates a display-required request. If successful,
// the screen is guaranteed not to turn off automatically due to user inactivity.
mDisplayRequest.RequestActive();
this.MessageBoard.Content = $"Display request activated - ScreenSaver suspended";
this.EnableButton.IsEnabled = true;
this.SuspendButton.IsEnabled = false;
}
catch (Exception ex)
{
this.MessageBoard.Content = $"Error: {ex.Message}";
}
}
}
}
private void EnableButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
if (mDisplayRequest != null)
{
try
{
// This call de-activates the display-required request. If successful, the screen
// might be turned off automatically due to a user inactivity, depending on the
// power policy settings of the system. The requestRelease method throws an exception
// if it is called before a successful requestActive call on this object.
mDisplayRequest.RequestRelease();
this.MessageBoard.Content = $"Display request released - ScreenSaver enabled.";
this.SuspendButton.IsEnabled = true;
this.EnableButton.IsEnabled = false;
}
catch (Exception ex)
{
this.MessageBoard.Content = $"Error: {ex.Message}";
}
}
}
}
}
}
<Window x:Class="SuspendScreenSaverWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SuspendScreenSaverWpf"
mc:Ignorable="d"
Title="MainWindow ScreenSaver management demo" Height="350" Width="525">
<Grid>
<Button x:Name="SuspendButton" IsEnabled="true" Content="Suspend ScreenSaver" HorizontalAlignment="Left" Margin="73,250,0,0" VerticalAlignment="Top" Width="150" Click="SuspendButton_Click"/>
<Button x:Name="EnableButton" IsEnabled="False" Content="Enable ScreenSaver" HorizontalAlignment="Left" Margin="298,250,0,0" VerticalAlignment="Top" Width="150" Click="EnableButton_Click"/>
<Label x:Name="MessageBoard" Content="Example project demonstrating how to disable ScreenSaver on Windows 10" HorizontalAlignment="Left" Height="78" Margin="73,39,0,0" VerticalAlignment="Top" Width="375"/>
</Grid>
</Window>
互操作方法在单独的类NativeMethods
中定义:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace ManageScreenSaver.MediaElementWpf
{
public static class NativeMethods
{
public const uint SPI_GETSCREENSAVETIMEOUT = 0x000E;
public const uint SPI_SETSCREENSAVETIMEOUT = 0x000F;
public const uint SPI_GETSCREENSAVEACTIVE = 0x0010;
public const uint SPI_SETSCREENSAVEACTIVE = 0x0011;
public const uint SPI_SETSCREENSAVERRUNNING = 0x0061;
public const uint SPI_SCREENSAVERRUNNING = SPI_SETSCREENSAVERRUNNING;
public const uint SPI_GETSCREENSAVERRUNNING = 0x0072;
public const uint SPI_GETSCREENSAVESECURE = 0x0076;
public const uint SPI_SETSCREENSAVESECURE = 0x0077;
public const uint SPIF_UPDATEINIFILE = 0x0001;
public const uint SPIF_SENDWININICHANGE = 0x0002;
public const uint SPIF_SENDCHANGE = SPIF_SENDWININICHANGE;
[DllImport("user32.dll", CallingConvention = CallingConvention.Winapi, PreserveSig = true, SetLastError = true)]
internal static unsafe extern bool SystemParametersInfo(uint uiAction, uint uiParam, void* pvParam, uint fWinIni);
[DllImport("user32.dll", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true)]
internal static extern IntPtr DefWindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled);
[DllImport("user32.dll", SetLastError = true)]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[DllImport("User32.dll", SetLastError = true)]
internal static extern int SendMessage(IntPtr hWnd, uint msg, uint wParam, uint lParam);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool LockWorkStation();
public static TimeSpan GetLastUserInputTimeInterval()
{
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
if (!GetLastInputInfo(ref lastInputInfo))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
uint ticks = (uint)Environment.TickCount;
var idleMiliseconds = ticks - lastInputInfo.dwTime;
return idleMiliseconds > 0 ? TimeSpan.FromMilliseconds((double)idleMiliseconds) : default(TimeSpan);
}
public static void LockWorkStationSession()
{
if (!LockWorkStation())
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
public static bool IsScreenSaverActive
{
get
{
bool enabled = false;
unsafe
{
var result = SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, &enabled, 0);
if (!result)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return enabled;
}
}
}
public static bool IsScreenSaverRunning
{
get
{
bool enabled = false;
unsafe
{
var result = SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, &enabled, 0);
if (!result)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return enabled;
}
}
}
public static bool IsScreenSaverSecure
{
get
{
bool enabled = false;
unsafe
{
var result = SystemParametersInfo(SPI_GETSCREENSAVESECURE, 0, &enabled, 0);
if (!result)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return enabled;
}
}
}
public static TimeSpan ScreenSaverTimeout
{
get
{
int timeout = 0;
unsafe
{
var result = SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, &timeout, 0);
if (!result)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return TimeSpan.FromSeconds(timeout);
}
}
}
}
[Flags]
public enum WindowMessage : uint
{
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
}
public enum WmSysCommandParam : uint
{
ScSIZE = 0xF000,
ScMOVE = 0xF010,
ScMINIMIZE = 0xF020,
ScMAXIMIZE = 0xF030,
ScNEXTWINDOW = 0xF040,
ScPREVWINDOW = 0xF050,
ScCLOSE = 0xF060,
ScVSCROLL = 0xF070,
ScHSCROLL = 0xF080,
ScMOUSEMENU = 0xF090,
ScKEYMENU = 0xF100,
ScARRANGE = 0xF110,
ScRESTORE = 0xF120,
ScTASKLIST = 0xF130,
ScSCREENSAVE = 0xF140,
ScHOTKEY = 0xF150,
ScDEFAULT = 0xF160,
ScMONITORPOWER= 0xF170,
ScCONTEXTHELP = 0xF180,
ScSEPARATOR = 0xF00F,
}
}
最后是关于如何在WPF应用程序中使用ScreenSaverManager
的示例:
<Window x:Class="ManageScreenSaver.MediaElementWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ManageScreenSaver.MediaElementWpf"
mc:Ignorable="d"
Title="MainWindow" Height="570" Width="550" MinHeight="570" MinWidth="550" MaxHeight="570" MaxWidth="550">
<Grid Margin="0,0,0,0">
<MediaElement x:Name="myMediaElement" Width="530" Height="270" LoadedBehavior="Manual" HorizontalAlignment="Center" VerticalAlignment="Center" IsMuted="True" Stretch="Fill" Margin="10,52,10,197" >
<MediaElement.Triggers>
<EventTrigger RoutedEvent="MediaElement.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<MediaTimeline Source="..\..\BigBuckBunny_320x180.mp4" Storyboard.TargetName="myMediaElement" RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</MediaElement.Triggers>
</MediaElement>
<Button x:Name="SuspendButton" IsEnabled="true" Content="Suspend ScreenSaver" HorizontalAlignment="Left" Margin="74,489,0,0" VerticalAlignment="Top" Width="150" Click="SuspendButton_Click" RenderTransformOrigin="0.501,2.334"/>
<Button x:Name="EnableButton" IsEnabled="true" Content="Enable ScreenSaver" HorizontalAlignment="Left" Margin="302,489,0,0" VerticalAlignment="Top" Width="150" Click="EnableButton_Click" RenderTransformOrigin="0.508,1.359"/>
<Label x:Name="MessageBoard" Content="Example project demonstrating how to disable ScreenSaver on Windows 10" HorizontalAlignment="Left" Height="25" Margin="44,10,0,0" VerticalAlignment="Top" Width="432"/>
<TextBox x:Name="TextBox" Text="" HorizontalAlignment="Center" HorizontalContentAlignment="Left" Height="110" Margin="10,342,10,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="510"/>
</Grid>
</Window>
using System;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using Windows.System.Display;
namespace ManageScreenSaver.MediaElementWpf
{
public partial class MainWindow : Window
{
private DisplayRequest mDisplayRequest;
internal static TextBoxWriter Console;
private static ScreenSaverManager _ScreenSaverManager;
public MainWindow()
{
InitializeComponent();
Console = new TextBoxWriter(this.TextBox);
_ScreenSaverManager = ScreenSaverManager.Instance;
PrintSSaverStatus(" MainWindow.ctor");
}
private void PrintSSaverStatus(string apendedText = "")
{
Console.WriteLine(GetScreenSaverStatusMessage() + apendedText);
}
private void SuspendButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
EnsureDisplayRequest();
if (mDisplayRequest != null)
{
try
{
// This call activates a display-required request. If successful,
// the screen is guaranteed not to turn off automatically due to user inactivity.
mDisplayRequest.RequestActive();
this.MessageBoard.Content = $"Display request activated - ScreenSaver suspended";
this.EnableButton.IsEnabled = true;
this.SuspendButton.IsEnabled = false;
}
catch (Exception ex)
{
this.MessageBoard.Content = $"Error: {ex.Message}";
}
PrintSSaverStatus(" SuspendButton_Click");
}
}
}
private void EnsureDisplayRequest()
{
try
{
if (mDisplayRequest == null)
{
// This call creates an instance of the displayRequest object
mDisplayRequest = new DisplayRequest();
}
}
catch (Exception ex)
{
this.MessageBoard.Content = $"Error Creating Display Request: {ex.Message}";
}
}
private void EnableButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
EnsureDisplayRequest();
if (mDisplayRequest != null)
{
try
{
// This call de-activates the display-required request. If successful, the screen
// might be turned off automatically due to a user inactivity, depending on the
// power policy settings of the system. The requestRelease method throws an exception
// if it is called before a successful requestActive call on this object.
mDisplayRequest.RequestRelease();
this.MessageBoard.Content = $"Display request released - ScreenSaver enabled.";
this.SuspendButton.IsEnabled = true;
this.EnableButton.IsEnabled = false;
}
catch (Exception ex)
{
this.MessageBoard.Content = $"Error: {ex.Message}";
}
PrintSSaverStatus(" EnableButton_Click");
}
}
}
private string GetScreenSaverStatusMessage()
{
string message = $"Screen Saver is: \"{{0}}\", \"{{1}}\", timeout: \"{{2}}\" {DateTime.UtcNow}";
message = String.Format(message,
NativeMethods.IsScreenSaverActive ? "active" : "inactive",
NativeMethods.IsScreenSaverSecure ? "secure" : "not secure",
NativeMethods.ScreenSaverTimeout);
return message;
}
}
}
注意:这不是可用于生产的代码。必须实现错误处理、系统和监控电源事件处理、登录和注销处理:工作站会话开始和结束、会话内屏幕保护程序配置更改
此方法有一些限制,当通过RDP连接到远程计算机时将不起作用,但当通过控制台连接到Hyper-V中的Windows VM时将起作用。谢谢!我会尝试那种方法。尝试那种。。。似乎不起作用:-(首先,我是通过Windows加载的函数完成的。之后,我尝试了Media Element初始化函数,最后,我使用了一个计时器事件,每秒钟设置一次屏幕保护程序。没有任何效果……但是,如果没有mediaelement播放,您的代码可以正常运行。这是一个挑战-让我们尝试完成它。我将调查它,然后让我们继续你们知道结果是什么。困难的问题已经用相对简单的方法解决了。看看新的编辑和代码列表:)
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace ManageScreenSaver.MediaElementWpf
{
public static class NativeMethods
{
public const uint SPI_GETSCREENSAVETIMEOUT = 0x000E;
public const uint SPI_SETSCREENSAVETIMEOUT = 0x000F;
public const uint SPI_GETSCREENSAVEACTIVE = 0x0010;
public const uint SPI_SETSCREENSAVEACTIVE = 0x0011;
public const uint SPI_SETSCREENSAVERRUNNING = 0x0061;
public const uint SPI_SCREENSAVERRUNNING = SPI_SETSCREENSAVERRUNNING;
public const uint SPI_GETSCREENSAVERRUNNING = 0x0072;
public const uint SPI_GETSCREENSAVESECURE = 0x0076;
public const uint SPI_SETSCREENSAVESECURE = 0x0077;
public const uint SPIF_UPDATEINIFILE = 0x0001;
public const uint SPIF_SENDWININICHANGE = 0x0002;
public const uint SPIF_SENDCHANGE = SPIF_SENDWININICHANGE;
[DllImport("user32.dll", CallingConvention = CallingConvention.Winapi, PreserveSig = true, SetLastError = true)]
internal static unsafe extern bool SystemParametersInfo(uint uiAction, uint uiParam, void* pvParam, uint fWinIni);
[DllImport("user32.dll", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true)]
internal static extern IntPtr DefWindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled);
[DllImport("user32.dll", SetLastError = true)]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[DllImport("User32.dll", SetLastError = true)]
internal static extern int SendMessage(IntPtr hWnd, uint msg, uint wParam, uint lParam);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool LockWorkStation();
public static TimeSpan GetLastUserInputTimeInterval()
{
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
if (!GetLastInputInfo(ref lastInputInfo))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
uint ticks = (uint)Environment.TickCount;
var idleMiliseconds = ticks - lastInputInfo.dwTime;
return idleMiliseconds > 0 ? TimeSpan.FromMilliseconds((double)idleMiliseconds) : default(TimeSpan);
}
public static void LockWorkStationSession()
{
if (!LockWorkStation())
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
public static bool IsScreenSaverActive
{
get
{
bool enabled = false;
unsafe
{
var result = SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, &enabled, 0);
if (!result)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return enabled;
}
}
}
public static bool IsScreenSaverRunning
{
get
{
bool enabled = false;
unsafe
{
var result = SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, &enabled, 0);
if (!result)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return enabled;
}
}
}
public static bool IsScreenSaverSecure
{
get
{
bool enabled = false;
unsafe
{
var result = SystemParametersInfo(SPI_GETSCREENSAVESECURE, 0, &enabled, 0);
if (!result)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return enabled;
}
}
}
public static TimeSpan ScreenSaverTimeout
{
get
{
int timeout = 0;
unsafe
{
var result = SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, &timeout, 0);
if (!result)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return TimeSpan.FromSeconds(timeout);
}
}
}
}
[Flags]
public enum WindowMessage : uint
{
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
}
public enum WmSysCommandParam : uint
{
ScSIZE = 0xF000,
ScMOVE = 0xF010,
ScMINIMIZE = 0xF020,
ScMAXIMIZE = 0xF030,
ScNEXTWINDOW = 0xF040,
ScPREVWINDOW = 0xF050,
ScCLOSE = 0xF060,
ScVSCROLL = 0xF070,
ScHSCROLL = 0xF080,
ScMOUSEMENU = 0xF090,
ScKEYMENU = 0xF100,
ScARRANGE = 0xF110,
ScRESTORE = 0xF120,
ScTASKLIST = 0xF130,
ScSCREENSAVE = 0xF140,
ScHOTKEY = 0xF150,
ScDEFAULT = 0xF160,
ScMONITORPOWER= 0xF170,
ScCONTEXTHELP = 0xF180,
ScSEPARATOR = 0xF00F,
}
}
<Window x:Class="ManageScreenSaver.MediaElementWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ManageScreenSaver.MediaElementWpf"
mc:Ignorable="d"
Title="MainWindow" Height="570" Width="550" MinHeight="570" MinWidth="550" MaxHeight="570" MaxWidth="550">
<Grid Margin="0,0,0,0">
<MediaElement x:Name="myMediaElement" Width="530" Height="270" LoadedBehavior="Manual" HorizontalAlignment="Center" VerticalAlignment="Center" IsMuted="True" Stretch="Fill" Margin="10,52,10,197" >
<MediaElement.Triggers>
<EventTrigger RoutedEvent="MediaElement.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<MediaTimeline Source="..\..\BigBuckBunny_320x180.mp4" Storyboard.TargetName="myMediaElement" RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</MediaElement.Triggers>
</MediaElement>
<Button x:Name="SuspendButton" IsEnabled="true" Content="Suspend ScreenSaver" HorizontalAlignment="Left" Margin="74,489,0,0" VerticalAlignment="Top" Width="150" Click="SuspendButton_Click" RenderTransformOrigin="0.501,2.334"/>
<Button x:Name="EnableButton" IsEnabled="true" Content="Enable ScreenSaver" HorizontalAlignment="Left" Margin="302,489,0,0" VerticalAlignment="Top" Width="150" Click="EnableButton_Click" RenderTransformOrigin="0.508,1.359"/>
<Label x:Name="MessageBoard" Content="Example project demonstrating how to disable ScreenSaver on Windows 10" HorizontalAlignment="Left" Height="25" Margin="44,10,0,0" VerticalAlignment="Top" Width="432"/>
<TextBox x:Name="TextBox" Text="" HorizontalAlignment="Center" HorizontalContentAlignment="Left" Height="110" Margin="10,342,10,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="510"/>
</Grid>
</Window>
using System;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using Windows.System.Display;
namespace ManageScreenSaver.MediaElementWpf
{
public partial class MainWindow : Window
{
private DisplayRequest mDisplayRequest;
internal static TextBoxWriter Console;
private static ScreenSaverManager _ScreenSaverManager;
public MainWindow()
{
InitializeComponent();
Console = new TextBoxWriter(this.TextBox);
_ScreenSaverManager = ScreenSaverManager.Instance;
PrintSSaverStatus(" MainWindow.ctor");
}
private void PrintSSaverStatus(string apendedText = "")
{
Console.WriteLine(GetScreenSaverStatusMessage() + apendedText);
}
private void SuspendButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
EnsureDisplayRequest();
if (mDisplayRequest != null)
{
try
{
// This call activates a display-required request. If successful,
// the screen is guaranteed not to turn off automatically due to user inactivity.
mDisplayRequest.RequestActive();
this.MessageBoard.Content = $"Display request activated - ScreenSaver suspended";
this.EnableButton.IsEnabled = true;
this.SuspendButton.IsEnabled = false;
}
catch (Exception ex)
{
this.MessageBoard.Content = $"Error: {ex.Message}";
}
PrintSSaverStatus(" SuspendButton_Click");
}
}
}
private void EnsureDisplayRequest()
{
try
{
if (mDisplayRequest == null)
{
// This call creates an instance of the displayRequest object
mDisplayRequest = new DisplayRequest();
}
}
catch (Exception ex)
{
this.MessageBoard.Content = $"Error Creating Display Request: {ex.Message}";
}
}
private void EnableButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
EnsureDisplayRequest();
if (mDisplayRequest != null)
{
try
{
// This call de-activates the display-required request. If successful, the screen
// might be turned off automatically due to a user inactivity, depending on the
// power policy settings of the system. The requestRelease method throws an exception
// if it is called before a successful requestActive call on this object.
mDisplayRequest.RequestRelease();
this.MessageBoard.Content = $"Display request released - ScreenSaver enabled.";
this.SuspendButton.IsEnabled = true;
this.EnableButton.IsEnabled = false;
}
catch (Exception ex)
{
this.MessageBoard.Content = $"Error: {ex.Message}";
}
PrintSSaverStatus(" EnableButton_Click");
}
}
}
private string GetScreenSaverStatusMessage()
{
string message = $"Screen Saver is: \"{{0}}\", \"{{1}}\", timeout: \"{{2}}\" {DateTime.UtcNow}";
message = String.Format(message,
NativeMethods.IsScreenSaverActive ? "active" : "inactive",
NativeMethods.IsScreenSaverSecure ? "secure" : "not secure",
NativeMethods.ScreenSaverTimeout);
return message;
}
}
}
using System;
using System.IO;
using System.Text;
using System.Windows.Controls;
namespace ManageScreenSaver.MediaElementWpf
{
public class TextBoxWriter : TextWriter
{
private TextBox _TextBox;
private string _NewLine = "\n";
public TextBoxWriter(TextBox target)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
_TextBox = target;
}
public override Encoding Encoding => new UTF8Encoding(false);
public override string NewLine { get => _NewLine; set => _NewLine = value; }
public override void Write(string value)
{
_TextBox.Dispatcher.InvokeAsync(
() => _TextBox.AppendText(value)
);
}
public override void WriteLine(string value)
{
_TextBox.Dispatcher.InvokeAsync(
() => _TextBox.AppendText(value + NewLine)
);
}
}
}