I wrote a smaall application in C #. I want this app to lock to unlock a workstation on my own input.
Locking a workstation is quite simple and works fine.
The problem starts when I want to unlock a workstation.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.Security.Principal;
using System.Security.Permissions;
using System.Drawing;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
[DllImport("User32.dll")]
public static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("User32.dll")]
public static extern void ReleaseDC(IntPtr dc);
IntPtr desktopDC;
Graphics g;
public static class Logon
{
[DllImport("User32.Dll", EntryPoint = "LockWorkStation"), Description("Locks the workstation display. Locking a workstation protects it from unauthorized use.")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool LockWorkStation();
public static void LockWorkstation()
{
if (!LockWorkStation())
throw new Win32Exception(Marshal.GetLastWin32Error());
}
[DllImport("advapi32.dll", EntryPoint = "LogonUser")]
public static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Logon.LockWorkstation();
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
Login();
}
private void Login()
{
string sUsername = "adam";
string sDomain = System.Environment.MachineName;
string sPassword = "sernik";
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
IntPtr pExistingTokenHandle = new IntPtr(0);
IntPtr pDuplicateTokenHandle = new IntPtr(0);
pExistingTokenHandle = IntPtr.Zero;
pDuplicateTokenHandle = IntPtr.Zero;
bool a = Logon.LogonUser(sUsername, sDomain, sPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
g.DrawString(a.ToString(), new Font(FontFamily.GenericSansSerif, 80), Brushes.Red, 100, 100);
}
private void button2_Click(object sender, EventArgs e)
{
Login();
}
private void Form1_Load(object sender, EventArgs e)
{
desktopDC = GetDC(IntPtr.Zero);
g = Graphics.FromHdc(desktopDC);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
g.Dispose();
ReleaseDC(desktopDC);
}
}
}
I tried to use the LogonUser method, but it only gives my true or false result and does not unlock the screen.
How to do it in Windows 7?
The application pie is to detect the presence of an electronic key connected to a PC, and then lock or unlock the workstation.
source
share