获取系统当前用户登录名的问题

hazrael 2007-05-28 03:41:28
在XP及以后的Windows系统中,在启动可执行程序时,可以选择使用其他用户的身份启动。现在有一个问题,如何在程序启动后,在程序中获得当前系统的用户名,而不是启动程序时的用户名?
例如:当前系统有两个用户a和b。登录a,并启动一个程序aaa.exe。启动时,选择使用b用户运行该程序。那么在程序中该如何进行判断,得到当前系统用户为a而不是b?
...全文
550 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
hazrael 2007-06-05
  • 打赏
  • 举报
回复
已解决,封帖
hazrael 2007-05-29
  • 打赏
  • 举报
回复
实际上,程序要求是这样的。
每个用户都有一个对应的数据目录。例如,在XP系统下,一般是C:\Document and Settings\<username>。
实际上问题想得到的结果是,在用户 UserA 登录系统后,使用用户 UserB 的身份启动程序pro.exe。那么使用什么方法,在程序pro.exe中,仍旧得到C:\Document and Settings\UserA这个目录,而不是C:\Document and Settings\UserB这个目录?
hazrael 2007-05-29
  • 打赏
  • 举报
回复
The GetUserName function retrieves the name of the user associated with the current thread.(MSDN)
所以,jinjazz(近身剪) 提出的解决方案应该够呛。
jinjazz 2007-05-28
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication25
{

public partial class Form1 : Form
{
[DllImport("Advapi32.dll", EntryPoint = "GetUserName",
ExactSpelling = false, SetLastError = true)]

static extern bool GetUserName(
[MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
[MarshalAs(UnmanagedType.LPArray)] Int32[] nSize);



public Form1()
{
InitializeComponent();
System.Text.StringBuilder b = new System.Text.StringBuilder(100);
int n = b.Capacity;
byte[] str = new byte[256];
Int32[] len = new Int32[1];
len[0] = 256;
GetUserName(str, len);
MessageBox.Show(System.Text.Encoding.ASCII.GetString(str));


string a;
a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

MessageBox.Show(a.ToString());
}
}
}
x_ch 2007-05-28
  • 打赏
  • 举报
回复
get hostname

17,740

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 .NET Framework
社区管理员
  • .NET Framework社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧