C#實現自動鎖屏+關屏

來源:互聯網
上載者:User

新近找到了windows鎖屏API:LockWorkStation

  於是乎把之前的關屏API整合了一下,弄了個可以選擇自動鎖屏+關屏的東東。

  如下程式碼片段:

  public Form1( bool aLock ) {

  if (aLock) {

  //鎖屏+關屏

  LockWorkStation();

  SendMessage( this.Handle, (uint)0x0112, (IntPtr)0xF170, (IntPtr)2 );

  }

  else {

  //禁止滑鼠鍵盤動作+關屏

  BlockInput( true );

  System.Threading.Thread.Sleep( 10 );

  SendMessage( this.Handle, (uint)0x0112, (IntPtr)0xF170, (IntPtr)2 );

  BlockInput( false );

  }

  this.Close();

  //Application.Exit();

  Environment.Exit( 0 );

  }

  //關屏

  [DllImport( "user32.dll", CharSet = CharSet.Auto )]

  static extern IntPtr SendMessage( IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam );

  //禁止滑鼠鍵盤動作

  [return: MarshalAs( UnmanagedType.Bool )]

  [DllImport( "user32.dll", CharSet = CharSet.Auto, ExactSpelling = true )]

  public static extern bool BlockInput( [In, MarshalAs( UnmanagedType.Bool )] bool fBlockIt );

  //鎖屏

  [DllImport( "user32.dll" )]

  public static extern bool LockWorkStation();

  需要指出的是,在退出程式時使用Environment.Exit( 0 );而非Application.Exit();否則會出錯哦~~提示類似:“***遇到錯誤,需要關閉”。

  還有就是修改一下Main:

  static void Main(string[] args) {

  //Application.EnableVisualStyles();

  //Application.SetCompatibleTextRenderingDefault( false );

  if (args == null || args.Length == 0) {

  //禁止滑鼠鍵盤動作+關屏

  Application.Run( new Form1( false ) );

  }

  else {

  //鎖屏+關屏

  Application.Run( new Form1( true ) );

  }

  }

  ..

  如此即可大功告成了。。。

  之所以要禁用滑鼠鍵盤,是為了關屏成功。。。~~~廢話。。。

  建立個捷徑,加個參數,即可鎖屏。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.