Powershell and winapi SystemParametersInfo function

狂风中的少年 提交于 2021-02-11 14:02:28

问题


I was trying this:

$f=@'
[DllImport("user32.dll")]public static extern int SystemParametersInfo(
    int uAction, 
    int uParam, 
    int lpvParam, 
    int fuWinIni
);
'@

$mSpeed = Add-Type -memberDefinition $f -name "mSpeed" -namespace Win32Functions -passThru
    
$get = 0x0070
$set = 0x0071
    
$srcSpeed = $mSpeed::SystemParametersInfo($get, 0, 0, 0)
    
$newSpeed = $srcSpeed + 1
    
$mSpeed::SystemParametersInfo($set, 0, $newSpeed, 0)

but the mouse speed does not return. How do I write this down correctly?


回答1:


According to the documentation, pvParam is the parameter that receives the current mouse speed, not the return value. The return value represents whether it is successful or not. It will return 0(failed) here, and then the 2nd call always sets the mouse speed to 1.

  • SPI_GETMOUSESPEED: pvParam is a point to an integer.
  • SPI_SETMOUSESPEED: It is an integer.

The equivalent C code is:

UINT pvParam = 0;
BOOL ret = 0;
ret = SystemParametersInfo(SPI_GETMOUSESPEED, 0, &pvParam, 0);
pvParam++;
ret = SystemParametersInfo(SPI_SETMOUSESPEED, 0, (LPVOID)pvParam, 0);

So you could declare its type as IntPtr

$f=@'
[DllImport("user32.dll")]public static extern int SystemParametersInfo(
    int uAction, 
    int uParam, 
    IntPtr lpvParam, 
    int fuWinIni
);
'@

And then create a IntPtr instance to receive the Integer, and read the Integer from the instance. Finally, conver the new value to a new IntPtr and call set method:

[IntPtr]$srcSpeedPtr = [system.runtime.interopservices.marshal]::AllocHGlobal(4)

$mSpeed::SystemParametersInfo($get, 0, $srcSpeedPtr, 0)
$srcSpeed = [system.runtime.interopservices.marshal]::ReadInt32($srcSpeedPtr, 0)
echo $srcSpeed

[IntPtr]$newSpeed = [IntPtr]::new($srcSpeed + 1)
$mSpeed::SystemParametersInfo($set, 0, $newSpeed, 0)

[system.runtime.interopservices.marshal]::FreeHGlobal($srcSpeedPtr)


来源:https://stackoverflow.com/questions/64249920/powershell-and-winapi-systemparametersinfo-function

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