GetUserNameA doesn't retrieve the latest user name

自古美人都是妖i 提交于 2021-01-28 18:50:24

问题


I have a function which uses windows api to get current windows user login (https://support.microsoft.com/en-nz/help/152970/visual-basic-procedure-to-get-current-user-name).

Private Declare PtrSafe Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

' Main routine to Dimension variables, retrieve user name.
Public Function WindowsUserName() As String

     ' Dimension variables
     Dim lpBuff As String * 25
     Dim ret As Long, UserName As String

     ' Get the user name minus any trailing spaces found in the name.
     ret = GetUserName(lpBuff, 25)
     WindowsUserName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)

End Function

Problem: if I renamed the windows user (in Windows 10), this function always get the old name, even though I login with the new name.

Is there anyway to retrieve the latest user name in VBA?

Updated: In few comments, the account name changed in Control Panel is display name, not user name. Now back to my question: Is there anyway to retrieve the latest DISPLAY name in VBA?


回答1:


There are some differences in user account management between OS Build 18362.356 and 18362.418. (There are some other versions between these two. I didn't test those versions.)

On OS Build 18362.356 you can see the below UI and settings. You can change the user name via Control Panel\User Accounts\User Accounts -> Manage User Accounts -> Properties. Either you change other account user name as a administrator or change your logged in account user name. After restart you can get the new user name using GetUserName API or command set username.

On OS Build 18362.418 you can see the below UI and settings. Based on your description you seems using this build version and result in this issue. I can also reproduce this issue on this build version.

On OS Build 18362.449 has the same UI and settings with 18362.356 as I showed above and I can't reproduce this issue on this build version.



来源:https://stackoverflow.com/questions/58497564/getusernamea-doesnt-retrieve-the-latest-user-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!