Step 1
Create a WPF Application and give solution name SolTurnOffMonitor.
Step 2
Add a button on window,it is look like this
<Window x:Class="SolTurnOffMonitor.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="TurnOffMonitor" Height="100" Width="200" Background="Gray" WindowStartupLocation="CenterScreen" WindowStyle="ToolWindow" ResizeMode="NoResize"> <Grid> <Button Content="TurnOff Monitor" Name="btnTurnOff" Foreground="Salmon" Click="btnTurnOff_Click" MouseMove="btnTurnOff_MouseMove"> <Button.Background> <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0"> <GradientStop Color="#FFF7B80D"/> <GradientStop Color="#FF1D1D1B" Offset="1"/> </LinearGradientBrush> </Button.Background> </Button> </Grid> </Window>
Step 3
Go to the code behind and add the following code,it is look like this
public partial class MainWindow : Window { #region Declaration const int SC_MONITORPOWER = 0xF170; const int WM_SYSCOMMAND = 0x0112; const int MONITOR_ON = 2; const int MONITOR_OFF =-1; const int MONITOR_STANBY = 1; [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam); #endregion #region Constructor public MainWindow() { InitializeComponent(); } #endregion #region Method /// <summary> /// Turn off Monitor /// </summary> private void TurnOffMonitor() { try { SendMessage(MONITOR_OFF, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_ON); } catch (Exception ex) { throw new Exception(ex.Message); } } #endregion #region Events /// <summary> /// When the button click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnTurnOff_Click(object sender, RoutedEventArgs e) { try { TurnOffMonitor(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// when the mouse move on button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnTurnOff_MouseMove(object sender, MouseEventArgs e) { try { TurnOffMonitor(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } #endregion }
SendMessage function
The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message.
Note
Turn off monitor when user click on button or move mouse cursor point to the button and turns them back on when the mouse moves outside the window.
Download
Download Source Code
No comments:
Post a Comment