C# SendKeyPress 并不总是把窗口放在前面

时间:2021-07-16 22:20:34

标签: c# winapi

在运行 Win 10 Pro 的 CNC 机器上,我有一个 C# 控制台应用程序,用于监视机器控制面板上的物理按钮按下情况。当按下按钮时,我使用 SendKeyPress 将其转发到 CNC 控制软件。

大多数情况下,这将 CNC 软件带到了前面,这正是我想要的。有时它只是在任务栏上闪烁图标。

有什么方法可以确保 CNC 软件始终处于最前面?这是一台专用的 CNC PC,因此这是一种理想的行为。

我使用的代码的相关部分是:

        if (mKeys == null)
        {
            // TODO:  Populate these from a config file
            mKeys = new BitToKey[] {
                new BitToKey(450, "{F8}"),
                new BitToKey(451, "%d"),         // % = ALT, + = SHIFT, ^ = CTRL
                new BitToKey(452, "")
            };
        }
        var processName = "cncm";

        for (var i = 0; i < mKeys.Length; i++)
        {
            Skinning.Plc.IOState ioSt;
            var ret = m_skin.plc.GetMemoryState(mKeys[i].Bit, out ioSt);
            if (ret == Skinning.ReturnCode.SUCCESS)
            {
                var state = ioSt == Skinning.Plc.IOState.IO_LOGICAL_1;
                if (state == true && mKeys[i].LastState == false)
                {
                    Console.WriteLine("PLC memory bit " + mKeys[i].Bit.ToString() + " set");
                    SendKeyPress(mKeys[i].Key, processName);
                }
                mKeys[i].LastState = state;
            }
            else
            {
                Console.WriteLine("PLC memory bit read failed");
                // Assume this fail was caused by skinnings failure to reach CNC12 (probably CNC12 was closed)
                m_skin = null;
                mKeys = null; // Resets previous key states
                return;
            }
        }

0 个答案:

没有答案
相关问题