I don't think there is a Windows developer who has not done this with his or her favorite programming language. So here is the C# version. Putting Windows in Sleep or Hibernate mode can be done with one line of code using the Windows.Forms.Application object's SetSuspendState method, and locking can be done using Win32's LockWorkStation function.

using System.Windows.Forms;

public partial class mainForm : Form
{        
    private void hybernateButton_Click(object sender, EventArgs e)
    {
        bool retVal = Application.SetSuspendState(PowerState.Hibernate, false, false);

        if (retVal == false)
            MessageBox.Show("Could not hybernate the system.");
    }

    private void sleepButton_Click(object sender, EventArgs e)
    {
        bool retVal = Application.SetSuspendState(PowerState.Suspend, false, false);

        if (retVal == false)
            MessageBox.Show("Could not suspend the system.");
    }
}

SetSuspendState takes three arguments and they are all required. The first is one of the constants of the enum called PowerState, which tells the method to sleep or hibernate. The second argument is a bool and when set to true, Windows is forced into sleep or hibernation. And the third is also a bool which if set to true stops Windows from restoring the system's power status to active on a wake event. So to put Windows into sleep or hibernate mode, and later restore it without any problem the second and third arguments should be false.

Calling the Win32's LockWorkStation function in the user32.dll file locks Windows. The function takes no arguments. To be able to call the function import user32.dll using DllImport.

using System.Runtime.InteropServices;

public partial class mainForm : Form
{        
    [DllImport("user32.dll", SetLastError = true)]
    static extern bool LockWorkStation();
    
    private void lockWinButton_Click(object sender, EventArgs e)
    {
        bool result = LockWorkStation();

        if (result == false)
        {
            // An error occured
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }
    }
}