C#小功能

已管理员方式启动程序

System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                //Application.Run(new Form1());
                if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    new Test();//入口
                }
                else
                {
                    //创建启动对象
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.UseShellExecute = true;
                    startInfo.WorkingDirectory = Environment.CurrentDirectory;
                    startInfo.FileName = Application.ExecutablePath;
                    //设置启动动作,确保以管理员身份运行
                    startInfo.Verb = "runas";
                    try
                    {
                        System.Diagnostics.Process.Start(startInfo);
                    }
                    catch
                    {
                        return;
                    }
                    //退出
                    Application.Exit();
                }

修改当前用户的登录密码

 /// <summary>
        /// 重置当前用户的密码
        /// </summary>
        /// <param name="password">新密码</param>
        public static void ResetUserPassword(string password)
        {
            string _Path = "WinNT://" + Environment.MachineName;
            DirectoryEntry machine = new DirectoryEntry(_Path); //获得计算机实例
            DirectoryEntry user = machine.Children.Find(Environment.UserName, "User"); //找得用户
            if (user != null)
            {
                user.Invoke("SetPassword", password); //用户密码
                user.CommitChanges();
            }
        }

删除Windows账号

 /// <summary>
        /// 删除Windows用户
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static bool DeleteWinUser(string username)
        {
            try
            {
                using (DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
                {
                    //删除存在用户
                    var delUser = localMachine.Children.Find(username, "user");
                    if (delUser != null)
                    {
                        localMachine.Children.Remove(delUser);
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }

        }

启用/禁用windows帐户

/// <summary>
        /// 启用/禁用windows帐户
        /// </summary>
        /// <param name="username"></param>
        public static void Disable(string username, bool isDisable)
        {
            var userDn = "WinNT://" + Environment.MachineName + "/" + username + ",user";
            DirectoryEntry user = new DirectoryEntry(userDn);
            user.InvokeSet("AccountDisabled", isDisable);
            user.CommitChanges();
            user.Close();
        }

设置程序路径为开机启动

 /// <summary>
        /// 将此路径的程序设置成开机启动
        /// </summary>
        /// <param name="path"></param>
        private void OpenStart(string path)
        {
            try
            {
                RegistryKey RKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                RKey.SetValue("SAGA", path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

删除当前名称的开机启动项

/// <summary>
        /// 删除当前名称的开机启动项
        /// </summary>
        /// <param name="Name"></param>
        private void DeleteSubKey(string Name)
        {
            RegistryKey reg = Registry.LocalMachine;
            RegistryKey run = reg.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
            try
            {
                run.DeleteValue(Name);
                MessageBox.Show("  当前应用程序已成功从注册表中删除!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                reg.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

判断是否拥有管理员权限

 /// <summary>
        /// 判断当时是否拥有管理员权限
        /// </summary>
        /// <returns></returns>
        public static bool IsPermissions()
        {
            WindowsIdentity id = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(id);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

替换壁纸

 [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

        /// <summary>
        /// 更换壁纸
        /// </summary>
        /// <param name="fileName">壁纸文件的路径</param>
        /// <returns>操作结果:true为更换成功,false为更换失败</returns>
        public static bool ChangeWallPaper(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return false;
            }
            if (File.Exists(fileName) == false)
            {
                return false;
            }

            fileName = Path.GetFullPath(fileName);
            var nResult = SystemParametersInfo(20, 1, fileName, 0x1 | 0x2); //更换壁纸
            if (nResult == 0)
            {
                return false;
            }
            else
            {
                RegistryKey hk = Registry.CurrentUser;
                RegistryKey run = hk.CreateSubKey(@"Control Panel\Desktop\");
                run.SetValue("Wallpaper", fileName);
                return true;
            }
        }

返回到桌面

 /// <summary>
        /// 返回桌面
        /// </summary>
        public void GoHome()
        {
            Type shellType = Type.GetTypeFromProgID("shell.application");
            object shell = Activator.CreateInstance(shellType);
            shellType.InvokeMember("ToggleDesktop", BindingFlags.InvokeMethod, null, shell, new object[] { });
        }

修改系统音量

#region 修改系统音量
        [DllImport("user32.dll")]
        static extern void keybd_event(byte bVk, byte bScan, UInt32 dwFlags, UInt32 dwExtraInfo);

        [DllImport("user32.dll")]
        static extern Byte MapVirtualKey(UInt32 uCode, UInt32 uMapType);

        private const byte VK_VOLUME_MUTE = 0xAD;
        private const byte VK_VOLUME_DOWN = 0xAE;
        private const byte VK_VOLUME_UP = 0xAF;
        private const UInt32 KEYEVENTF_EXTENDEDKEY = 0x0001;
        private const UInt32 KEYEVENTF_KEYUP = 0x0002;

        /// <summary>
        /// 改变系统音量大小,增加
        /// </summary>
        public void VolumeUp()
        {
            keybd_event(VK_VOLUME_UP, MapVirtualKey(VK_VOLUME_UP, 0), KEYEVENTF_EXTENDEDKEY, 0);
            keybd_event(VK_VOLUME_UP, MapVirtualKey(VK_VOLUME_UP, 0), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
        }

        /// <summary>
        /// 改变系统音量大小,减小
        /// </summary>
        public void VolumeDown()
        {
            keybd_event(VK_VOLUME_DOWN, MapVirtualKey(VK_VOLUME_DOWN, 0), KEYEVENTF_EXTENDEDKEY, 0);
            keybd_event(VK_VOLUME_DOWN, MapVirtualKey(VK_VOLUME_DOWN, 0), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
        }

        /// <summary>
        /// 改变系统音量大小,静音
        /// </summary>
        public void Mute()
        {
            keybd_event(VK_VOLUME_MUTE, MapVirtualKey(VK_VOLUME_MUTE, 0), KEYEVENTF_EXTENDEDKEY, 0);
            keybd_event(VK_VOLUME_MUTE, MapVirtualKey(VK_VOLUME_MUTE, 0), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
        }



        #endregion

复制文件到另外一个地方并隐藏

 /// <summary>
        /// 拷贝文件到另一个文件夹下
        /// </summary>
        /// <param name="sourceName">源文件路径</param>
        /// <param name="folderPath">目标路径(目标文件夹)</param>
        public void CopyToFile(string sourceName, string folderPath)
        {
            //例子:
            //源文件路径
            //string sourceName = @"D:\Source\Test.txt";
            //目标路径:项目下的NewTest文件夹,(如果没有就创建该文件夹)
            //string folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NewTest");

            if (!Directory.Exists(folderPath))
            {
                //创建并隐藏
                Directory.CreateDirectory(folderPath).Attributes = FileAttributes.Hidden;
            }

            //当前文件如果不用新的文件名,那么就用原文件文件名
            string fileName = "WindowsService.exe";
            //这里可以给文件换个新名字,如下:
            //string fileName = string.Format("{0}.{1}", "newFileText", "txt");

            //目标整体路径
            string targetPath = Path.Combine(folderPath, fileName);

            //Copy到新文件下
            FileInfo file = new FileInfo(sourceName);
            if (file.Exists)
            {
                //true 为覆盖已存在的同名文件,false 为不覆盖
                file.CopyTo(targetPath, true);
            }
        }

获取当前计算机的名称

 /// <summary>
        /// 获取当前计算机名称
        /// </summary>
        /// <returns></returns>
        private string GetName()
        {
            return Environment.MachineName + "  ||  " + Environment.UserName;
        }

byte转文件

 /// <summary>
        /// byte转文件 path(D:\saga.png)
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="path"></param>
        public void GetVoiceAddress(byte[] bt,string path)
        {
            using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                fsWrite.Write(bt, 0, bt.Length);
            }
        }

获取本机ip地址

 /// <summary>
        /// 获取本地的IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIp()
        {
            //获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }

关闭程序

             try
            {
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Process.GetCurrentProcess().Kill();
            }

卸载当前程序

 /// <summary>
        /// 卸载当前程序
        /// </summary>
        /// <param name="delaySecond">多少秒后</param>
        private void DelayDeleteFile(int delaySecond = 2)
        {
            try
            {
                var fileName = Process.GetCurrentProcess().MainModule.FileName;
                fileName = Path.GetFullPath(fileName);
                var folder = Path.GetDirectoryName(fileName);
                var currentProcessFileName = Path.GetFileName(fileName);

                var arguments = $"/c timeout /t {delaySecond} && DEL /f {currentProcessFileName} ";

                var processStartInfo = new ProcessStartInfo()
                {
                    Verb = "runas", // 如果程序是管理员权限,那么运行 cmd 也是管理员权限
                    FileName = "cmd",
                    UseShellExecute = false,
                    CreateNoWindow = true, // 如果需要隐藏窗口,设置为 true 就不显示窗口
                    Arguments = arguments,
                    WorkingDirectory = folder,
                };

                Process.Start(processStartInfo);
                try
                {
                    Environment.Exit(0);
                }
                catch (Exception ex)
                {
                    Process.GetCurrentProcess().Kill();
                }
            }
            catch (Exception ex)
            {
                
            }
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值