1. 程式人生 > 其它 >rust小練習-01-新增滑鼠右鍵此處開啟CMD

rust小練習-01-新增滑鼠右鍵此處開啟CMD

安裝包

Caogo.toml 中,新增 winreg 包(操作登錄檔),用rust實現純屬小小練習。
在這裡插入圖片描述
cmd 進入專案中,cargo build 安裝,如果想檢視 winreg 的 API 和使用介紹,cmd 進入專案中 cargo doc 即可生成本地的所有你用到的庫的文件。

使用

程式碼內容很簡單,直接貼上了。

extern crate winreg;

use winreg::enums::HKEY_CLASSES_ROOT;
use winreg::{RegKey, RegValue};
use winreg::enums::*;
use std::io;

// 添加註冊表
fn start_add
() -> io::Result<()> { println!("\nStarting reading windows reg..."); let my_key = RegKey::predef(HKEY_CLASSES_ROOT); let (my_key, disposition) = my_key.create_subkey("Directory\\Background\\shell\\runas")?; match disposition { REG_CREATED_NEW_KEY =
> println!("==step 1 runas created, succeed."), REG_OPENED_EXISTING_KEY => println!("==runas already exist, skip 1") } my_key.set_value("", &"Open Cmd Here")?; // 0x639bc8 Vec中倒序存入 let keys: Vec<u8> = vec![200, 155, 99,
0]; let data = RegValue {vtype: REG_DWORD, bytes: keys}; my_key.set_raw_value("ShowBasedOnVelocityId", &data)?; let (my_key, disposition) = my_key.create_subkey("command")?; match disposition { REG_CREATED_NEW_KEY => println!("==step 2 runas-command created, succeed."), REG_OPENED_EXISTING_KEY => println!("==runas-command already exist, skip 2") } my_key.set_value("", &"cmd.exe /s /k pushd \"%V\"")?; Ok(()) } // 刪除登錄檔 fn delete_it() -> io::Result<()> { RegKey::predef(HKEY_CLASSES_ROOT) .delete_subkey_all("Directory\\Background\\shell\\runas")?; Ok(()) } fn main() { println!("\nInput 1 to add, 2 to delete, other noting done."); let mut input = String::new(); io::stdin().read_line(&mut input) .expect("Read input failed."); let input : u32 = input.trim().parse() .expect("Please input a num."); if input == 1 { let result = start_add(); match result { Ok(()) => println!("\nADD FUNCTION END."), Err(error) => { panic!("ADD FAILED : {:?}", error) } } } else if input == 2 { let result = delete_it(); match result { Ok(()) => println!("\nDELETE FUNCTION END."), Err(error) => { match error.kind() { // 如果要刪除的鍵,不存在。 io::ErrorKind::NotFound => println!("no purpose exist, no need to delete."), _ => panic!("DELETE FAILED : {:?}", error) } } } } else { println!("Nothing to do."); } }

結果

新增前:
在這裡插入圖片描述
執行程式(需要管理員執行):
在這裡插入圖片描述
新增後:
在這裡插入圖片描述