Search code examples
c#.netwinformswindows-hello

Windows Hello validation with C# Windows Forms App (.NET Framework)?


Can I write a code block that opens the Windows Hello window when the button is clicked and takes action according to the correctness of the password? If I could write, how would I do it?

I'm working on: Windows Forms .NET Framework (C#)


Solution

  • For a .NET Framework WinForms application, you need to follow these steps:

    1. Tools → NuGet Package Manager → Package Manager Settings → Make sure PackageReference is selected for Default package management format.
    2. Solution Explorer → Right click on your project → choose Manage NuGet Packages.
    3. In the Browse tab of the package manager, search for Microsoft.Windows.SDK.Contracts package. In the right pane of the NuGet Package Manager window select the desired version of the package based on the version of Windows 10 you want to target and click install.
    4. Then search for Microsoft.NETCore.UniversalWindowsPlatform package and install it.
    5. Add the following code in the application, for example in a button click handler:
      // Required using statements:
      // using Windows.Security.Credentials;
      private async void button1_Click(object sender, EventArgs e)
      {
          bool supported = await KeyCredentialManager.IsSupportedAsync();
          if (supported)
          {
              KeyCredentialRetrievalResult result =
                  await KeyCredentialManager.RequestCreateAsync("login", 
                  KeyCredentialCreationOption.ReplaceExisting);
              if (result.Status == KeyCredentialStatus.Success)
              {
                  MessageBox.Show("Logged in.");
              }
              else
              {
                  MessageBox.Show("Login failed.");
              }
          }
      }
      

    Here is the result:

    enter image description here

    To learn more, take a look at the following docs: