简体   繁体   English

如何从Windows操作系统获取当前用户名和密码。

[英]How get Current Username and password from windows operating System.

Story: I have a motherboard CD provided by Intel's original motherboard. 故事:我有英特尔原装主板提供的主板CD。 When I install drivers it asks for username and password of the administrator account. 当我安装驱动程序时,它会询问管理员帐户的用户名和密码。

After every driver installs, the system will be restart and doesn't ask for the username and password. 安装每个驱动程序后,系统将重新启动,并且不会要求输入用户名和密码。

My idea is that Windows should have a way to validate and enter username and password 我的想法是Windows应该有办法验证并输入用户名和密码

Could you please let me know how to do this in C#, thanks. 你能否告诉我如何在C#中做到这一点,谢谢。

I think this article might help you. 我认为这篇文章可能会对你有帮助。

Let me know if you face any problem while understanding the code. 如果您在理解代码时遇到任何问题,请告诉我。

Edit 1 : I am confused with your question. 编辑1:我对你的问题感到困惑。

my idea: According above Windows shoud be provide some vay to validate and enter username and password 我的想法:根据上面的Windows,请提供一些验证并输入用户名和密码的vay

Do you want to validate a entered username and password? 您想验证输入的用户名和密码吗?


Ahh, sorry for the delay. 啊,抱歉延误了。 Here's the converted c# code 这是转换后的c#代码

Add following namespaces: 添加以下命名空间:

using System.Security.Principal;
using System.Security.Permissions;
using System.Runtime.InteropServices;

And then here goes the main code : 接下来是主要代码:

namespace WindowsAccount
{
    public partial class Form1 : Form
    {

        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(string lpszUsername,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            out IntPtr phToken
            );

        [DllImport("kernel32.dll")]
        public static extern int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, ref IntPtr Arguments);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool CloseHandle(IntPtr hObject);


        public static string GetErrorMessage(int errorCode)
        {
            int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x100;
            int FORMAT_MESSAGE_IGNORE_INSERTS = 0x200;
            int FORMAT_MESSAGE_FROM_SYSTEM = 0x1000;

            int msgSize = 255;
            string lpMsgBuf = null;
            int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;

            IntPtr lpSource = IntPtr.Zero;
            IntPtr lpArguments = IntPtr.Zero;
            int returnVal = FormatMessage(dwFlags, ref lpSource, errorCode, 0, ref lpMsgBuf, msgSize, ref lpArguments);

            if (returnVal == 0)
            {
                throw new Exception("Failed to format message for error code " + errorCode.ToString() + ". ");
            }
            return lpMsgBuf;

        }


        public Form1()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            IntPtr tokenHandle = new IntPtr(0);

            try
            {
                string UserName = null;
                string MachineName = null;
                string Pwd = null;

                //The MachineName property gets the name of your computer.
                MachineName = System.Environment.MachineName;
                UserName = txtUser.Text;
                Pwd = txtPass.Text;

                const int LOGON32_PROVIDER_DEFAULT = 0;
                const int LOGON32_LOGON_INTERACTIVE = 2;
                tokenHandle = IntPtr.Zero;

                //Call the LogonUser function to obtain a handle to an access token.
                bool returnValue = LogonUser(UserName, MachineName, Pwd, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out tokenHandle);

                if (returnValue == false)
                {
                    //This function returns the error code that the last unmanaged function returned.
                    int ret = Marshal.GetLastWin32Error();
                    string errmsg = GetErrorMessage(ret);
                    MessageBox.Show(errmsg);
                }
                else
                {
                    //Create the WindowsIdentity object for the Windows user account that is
                    //represented by the tokenHandle token.

                    WindowsIdentity newId = new WindowsIdentity(tokenHandle);
                    WindowsPrincipal userperm = new WindowsPrincipal(newId);

                    //Verify whether the Windows user has administrative credentials.
                    if (userperm.IsInRole(WindowsBuiltInRole.Administrator))
                    {
                        MessageBox.Show("Access Granted. User is admin");
                    }
                    else
                    {
                        MessageBox.Show("Access Granted. User is not admin");
                    }
                }

                CloseHandle(tokenHandle);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception occurred. " + ex.Message);
            }

        }
    }
}

Let me know if you face any problem. 如果您遇到任何问题,请告诉我。

You can use the Auto Admin Login feature, which is controlled by a few registry keys. 您可以使用自动管理员登录功能,该功能由几个注册表项控制。 See http://support.microsoft.com/kb/315231 请参见http://support.microsoft.com/kb/315231

You can find out your username by going to a command prompt and typing: 您可以通过转到命令提示符并键入以下内容来找到您的用户名:

C:\ >set USERNAME

and it will print something like 它会打印出类似的东西

USERNAME=Administrator

that's your logged in username. 那是你登录的用户名。

I'm pretty sure your password is empty/blank because otherwise it would prompt you. 我很确定你的密码是空的/空白的,否则它会提示你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从代码获取Windows身份验证的用户名和密码 - How to get username and password of windows authentication from code 如何获取当前用户的用户名,密码和域 - How to get username, password and domain of current user 如何知道我目前的操作系统是否是C#中的Windows Vista? - How to know if my current operating system is Windows Vista in C#? 如何获取和更改Windows凭据用户名和密码 - How to Get and Change Windows Credential Username and Password ".NET Standard 2.0 获取当前操作系统" - .NET Standard 2.0 get current Operating System 如何使用.NET从多用户环境中的Windows Service获取当前Windows用户名 - How to get current windows username from windows service in multiuser environment using .NET 如何从用户名和密码获取WindowsPrincipal - How to get WindowsPrincipal from username and password 操作系统不支持的选定整理顺序。 WinXP的 - Selected collating sequence not supported by the operating system. WinXP 错误消息'此操作系统不支持指定的区域设置。 - Error message 'The specified locale is not supported on this operating system.' 此操作系统不支持区域设置 ID。 LCID=8192 - Locale id is not supported on this operating system. LCID=8192
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM