C#使用32位作为目标平台时启动软键盘(osk.exe)失败

snow_pear 发布于 12/04 14:48
阅读 39
收藏 0

在64位下启动正常,但是32位下启动失败。

因为某些原因,我的程序只能使用32位来编译。

32位下启动会直接报系统找不到文件的异常,我使用File.Exists也是直接返回false。请问以下32位方式编译如何才能启动osk.exe或者有没有其它的方式使用软键盘。

这是我的代码:

void StartOSK()
{
    string oskPath = Path.Combine(Environment.SystemDirectory, "osk.exe");
    if (File.Exists(oskPath))
    {
        Process.Start(oskPath);
    }
}

 

加载中
0
snow_pear
snow_pear

已经解决了。附上源代码。

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool Wow64RevertWow64FsRedirection(IntPtr ptr);

public const UInt32 WM_SYSCOMMAND = 0x112;
public const UInt32 SC_RESTORE = 0xf120;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
string OnScreenKeyboadApplication = "osk.exe";
string processName = Path.GetFileNameWithoutExtension(OnScreenKeyboadApplication);

Process[] keyboardProcess = Process.GetProcessesByName(processName);

// launch it if it doesn't exist
if (keyboardProcess.Length == 0)
{
    IntPtr ptr = new IntPtr(); ;
    bool sucessfullyDisabledWow64Redirect = false;

    // Disable x64 directory virtualization if we're on x64,
    // otherwise keyboard launch will fail.
    if (Environment.Is64BitOperatingSystem)
    {
        sucessfullyDisabledWow64Redirect = Program.Wow64DisableWow64FsRedirection(ref ptr);
    }

    // osk.exe is in windows/system folder. So we can directky call it without path
    using (Process osk = new Process())
    {
        osk.StartInfo.FileName = OnScreenKeyboadApplication;
        osk.Start();
        //osk.WaitForInputIdle(2000);
    }

    // Re-enable directory virtualisation if it was disabled.
    if (Environment.Is64BitOperatingSystem)
        if (sucessfullyDisabledWow64Redirect)
            Program.Wow64RevertWow64FsRedirection(ptr);
}
else
{
    // Bring keyboard to the front if it's already running
    var windowHandle = keyboardProcess[0].MainWindowHandle;
    Program.SendMessage(windowHandle, Program.WM_SYSCOMMAND, new IntPtr(Program.SC_RESTORE), new IntPtr(0));
}

这段代码必须在主线程中运行,否则一样找不到osk的路径。

来源:http://www.it1352.com/36902.html

返回顶部
顶部