当前位置: 首页 > news >正文

【C#】获取我的电脑的名字,如This PC、这台计算机

原文: 【C#】获取"我的电脑"的名字,如This PC、这台计算机

注意:这里获取的【我的电脑】的名字,不是机器的名字。如图所示:


要获取的是This PC这个字符串。

-------------------------------------------------------------------

机器的名字可以通过系统属性查看,叫做Computer Name,如下图:


我的就是cn-c-w-725,如果想获取这个字符串直接调用Environment.MachineName就行了。

1.定义ShellAPI

 public static class ShellAPI
    {

        public const int MAX_PATH = 260;
        public const uint CMD_FIRST = 1;
        public const uint CMD_LAST = 30000;

        public const int S_OK = 0, S_FALSE = 1;
        public const int DRAGDROP_S_DROP = 0x00040100;
        public const int DRAGDROP_S_CANCEL = 0x00040101;
        public const int DRAGDROP_S_USEDEFAULTCURSORS = 0x00040102;

        public static int cbFileInfo = Marshal.SizeOf(typeof(SHFILEINFO));



        // Retrieves information about an object in the file system,
        // such as a file, a folder, a directory, or a drive root.
        [DllImport("shell32",
            EntryPoint = "SHGetFileInfo",
            ExactSpelling = false,
            CharSet = CharSet.Auto,
            SetLastError = true)]
        public static extern IntPtr SHGetFileInfo(
            IntPtr ppidl,
            FILE_ATTRIBUTE dwFileAttributes,
            ref SHFILEINFO sfi,
            int cbFileInfo,
            SHGFI uFlags);

        [DllImport("Shell32",
            EntryPoint = "SHGetSpecialFolderLocation",
            ExactSpelling = true,
            CharSet = CharSet.Ansi,
            SetLastError = true)]
        public static extern Int32 SHGetSpecialFolderLocation(
            IntPtr hwndOwner,
            CSIDL nFolder,
            out IntPtr ppidl);

        // This function takes the fully-qualified pointer to an item
        // identifier list (PIDL) of a namespace object, and returns a specified
        // interface pointer on the parent object.


        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public SFGAO dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }
        // Flags that specify the file information to retrieve with SHGetFileInfo
        [Flags]
        public enum FILE_ATTRIBUTE
        {
            READONLY = 0x00000001,
            HIDDEN = 0x00000002,
            SYSTEM = 0x00000004,
            DIRECTORY = 0x00000010,
            ARCHIVE = 0x00000020,
            DEVICE = 0x00000040,
            NORMAL = 0x00000080,
            TEMPORARY = 0x00000100,
            SPARSE_FILE = 0x00000200,
            REPARSE_POINT = 0x00000400,
            COMPRESSED = 0x00000800,
            OFFLINE = 0x00001000,
            NOT_CONTENT_INDEXED = 0x00002000,
            ENCRYPTED = 0x00004000
        }
        // The attributes that the caller is requesting, when calling IShellFolder::GetAttributesOf
        [Flags]
        public enum SFGAO : uint
        {
            BROWSABLE = 0x8000000,
            CANCOPY = 1,
            CANDELETE = 0x20,
            CANLINK = 4,
            CANMONIKER = 0x400000,
            CANMOVE = 2,
            CANRENAME = 0x10,
            CAPABILITYMASK = 0x177,
            COMPRESSED = 0x4000000,
            CONTENTSMASK = 0x80000000,
            DISPLAYATTRMASK = 0xfc000,
            DROPTARGET = 0x100,
            ENCRYPTED = 0x2000,
            FILESYSANCESTOR = 0x10000000,
            FILESYSTEM = 0x40000000,
            FOLDER = 0x20000000,
            GHOSTED = 0x8000,
            HASPROPSHEET = 0x40,
            HASSTORAGE = 0x400000,
            HASSUBFOLDER = 0x80000000,
            HIDDEN = 0x80000,
            ISSLOW = 0x4000,
            LINK = 0x10000,
            NEWCONTENT = 0x200000,
            NONENUMERATED = 0x100000,
            READONLY = 0x40000,
            REMOVABLE = 0x2000000,
            SHARE = 0x20000,
            STORAGE = 8,
            STORAGEANCESTOR = 0x800000,
            STORAGECAPMASK = 0x70c50008,
            STREAM = 0x400000,
            VALIDATE = 0x1000000
        }
        // Used to retrieve directory paths to system special folders
        public enum CSIDL
        {
            ADMINTOOLS = 0x30,
            ALTSTARTUP = 0x1d,
            APPDATA = 0x1a,
            BITBUCKET = 10,
            CDBURN_AREA = 0x3b,
            COMMON_ADMINTOOLS = 0x2f,
            COMMON_ALTSTARTUP = 30,
            COMMON_APPDATA = 0x23,
            COMMON_DESKTOPDIRECTORY = 0x19,
            COMMON_DOCUMENTS = 0x2e,
            COMMON_FAVORITES = 0x1f,
            COMMON_MUSIC = 0x35,
            COMMON_PICTURES = 0x36,
            COMMON_PROGRAMS = 0x17,
            COMMON_STARTMENU = 0x16,
            COMMON_STARTUP = 0x18,
            COMMON_TEMPLATES = 0x2d,
            COMMON_VIDEO = 0x37,
            CONTROLS = 3,
            COOKIES = 0x21,
            DESKTOP = 0,
            DESKTOPDIRECTORY = 0x10,
            DRIVES = 0x11,
            FAVORITES = 6,
            FLAG_CREATE = 0x8000,
            FONTS = 20,
            HISTORY = 0x22,
            INTERNET = 1,
            INTERNET_CACHE = 0x20,
            LOCAL_APPDATA = 0x1c,
            MYDOCUMENTS = 12,
            MYMUSIC = 13,
            MYPICTURES = 0x27,
            MYVIDEO = 14,
            NETHOOD = 0x13,
            NETWORK = 0x12,
            PERSONAL = 5,
            PRINTERS = 4,
            PRINTHOOD = 0x1b,
            PROFILE = 40,
            PROFILES = 0x3e,
            PROGRAM_FILES = 0x26,
            PROGRAM_FILES_COMMON = 0x2b,
            PROGRAMS = 2,
            RECENT = 8,
            SENDTO = 9,
            STARTMENU = 11,
            STARTUP = 7,
            SYSTEM = 0x25,
            TEMPLATES = 0x15,
            WINDOWS = 0x24
        }

        // Defines the values used with the IShellFolder::GetDisplayNameOf and IShellFolder::SetNameOf 
        // methods to specify the type of file or folder names used by those methods

        // Flags that specify the file information to retrieve with SHGetFileInfo
        [Flags]
        public enum SHGFI : uint
        {
            ADDOVERLAYS = 0x20,
            ATTR_SPECIFIED = 0x20000,
            ATTRIBUTES = 0x800,
            DISPLAYNAME = 0x200,
            EXETYPE = 0x2000,
            ICON = 0x100,
            ICONLOCATION = 0x1000,
            LARGEICON = 0,
            LINKOVERLAY = 0x8000,
            OPENICON = 2,
            OVERLAYINDEX = 0x40,
            PIDL = 8,
            SELECTED = 0x10000,
            SHELLICONSIZE = 4,
            SMALLICON = 1,
            SYSICONINDEX = 0x4000,
            TYPENAME = 0x400,
            USEFILEATTRIBUTES = 0x10
        }

    }


2.调用输出显示

 static void Main(string[] args)
        {
            IntPtr tempPidl;
            ShellAPI.SHFILEINFO info;
            
            //My Computer
            info = new ShellAPI.SHFILEINFO();
            tempPidl = IntPtr.Zero;
            ShellAPI.SHGetSpecialFolderLocation(IntPtr.Zero, ShellAPI.CSIDL.DRIVES, out tempPidl);

            ShellAPI.SHGetFileInfo(tempPidl, 0, ref info, ShellAPI.cbFileInfo,
                ShellAPI.SHGFI.PIDL | ShellAPI.SHGFI.DISPLAYNAME | ShellAPI.SHGFI.TYPENAME);

            string sysfolderName = info.szTypeName;
            string mycompName = info.szDisplayName;
            Console.WriteLine(sysfolderName + "------" + mycompName);
            Console.WriteLine(Environment.MachineName);
            Console.Read();
        }

mycompName就是我们想要的值.

3.再介绍一个用winform编写的功能很强大的文件管理器。与自带的差不多,调用了系统的Shell api,可以获取到特殊路径的名称,对于没有权限操作的文件会进行动态请求。如图:


CodeProject地址

如果打不开,请去csdn下载。


进阶-参考另外一篇文章《【C#】WindowsAPICodePack-Shell使用教程》,地址:http://blog.csdn.net/catshitone/article/details/72723927


相关文章:

  • 对缓存使用的一些思考
  • nginx负载均衡及配置
  • 构建自己的php扩展函数
  • 基于wpf的skyline三维二次开发框架
  • 高性能缓存服务器 nuster v1.8.8.2 和 v1.7.11.2 发布
  • Centos7配置网络
  • 原生js如何实现图片翻转旋转效果?
  • mtools-你可能没用过的mongodb神器
  • 代码生成器技术乱弹四,弹性万能界面
  • Python函数参数全面介绍
  • 智能指针类模板(五十)
  • TreeMap分析(下)
  • 深入响应式原理--Vue
  • 页面a标签用js或jquery模拟点击
  • python的open函数
  • 【140天】尚学堂高淇Java300集视频精华笔记(86-87)
  • 2019.2.20 c++ 知识梳理
  • es6--symbol
  • LeetCode18.四数之和 JavaScript
  • mockjs让前端开发独立于后端
  • 汉诺塔算法
  • 缓存与缓冲
  • 模仿 Go Sort 排序接口实现的自定义排序
  • 一个项目push到多个远程Git仓库
  • 教程:使用iPhone相机和openCV来完成3D重建(第一部分) ...
  • 浅谈sql中的in与not in,exists与not exists的区别
  • ​HTTP与HTTPS:网络通信的安全卫士
  • ​io --- 处理流的核心工具​
  • # 达梦数据库知识点
  • #Linux(帮助手册)
  • (a /b)*c的值
  • (C语言)fgets与fputs函数详解
  • (Redis使用系列) SpirngBoot中关于Redis的值的各种方式的存储与取出 三
  • (论文阅读31/100)Stacked hourglass networks for human pose estimation
  • (未解决)macOS matplotlib 中文是方框
  • (一)u-boot-nand.bin的下载
  • (转)机器学习的数学基础(1)--Dirichlet分布
  • .desktop 桌面快捷_Linux桌面环境那么多,这几款优秀的任你选
  • .net framework profiles /.net framework 配置
  • .Net中ListT 泛型转成DataTable、DataSet
  • @data注解_一枚 架构师 也不会用的Lombok注解,相见恨晚
  • @Documented注解的作用
  • [ IOS ] iOS-控制器View的创建和生命周期
  • [20171102]视图v$session中process字段含义
  • [Android学习笔记]ScrollView的使用
  • [BUUCTF]-PWN:wustctf2020_number_game解析(补码,整数漏洞)
  • [BZOJ3223]文艺平衡树
  • [C puzzle book] types
  • [C/C++]关于C++11中的std::move和std::forward
  • [Firefly-Linux] RK3568 pca9555芯片驱动详解
  • [IE编程] WebBrowser控件的多页面浏览(Tabbed Browsing)开发接口
  • [IE编程] 如何设置IE8的WebBrowser控件(MSHTML) 的渲染模式
  • [InnoDB系列] -- SHOW INNODB STATUS 探秘
  • [Linux] Ubuntu install Miniconda
  • [moka同学笔记]yii表单dropdownlist样式