次のコードを使用して、特定の時刻にキーボードの状態にアクセスします。C#キーボードクラスを使用するDLL関数を書くにはどうすればいいですか
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Windows.Input;
namespace some.any
{
public class ANY_CLASS
{
[STAThread] //seems to do nothing here
public static short ThisIsCalledByAnExternalProgram()
{
try
{
if (Keyboard.IsKeyDown(Key.LeftAlt))
{
return 1;
}
else
{
return 0;
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return 2;
}
}
}
このコードはコンパイルするいくつかのDLLが必要です。WindowsBase.dllとPresentationCore.dll
キーボードは通常、私はmain関数に[STAThread]属性を記述し、それがうまくいく、STAスレッドを必要とし、このコードはdllとして使用されるので、私はそれを行うことはできません。私の関数ThisIsCalledByAnExternalProgram()はSTAとして実行する必要がありますが、それはdoesntです。
このコードをDLLとして使用するにはどうすればよいですか?
EDIT: STAThreadフラグ付きメソッド内でThisIsCalledByAnExternalProgram()を呼び出すとどうなりますか?
私の外部プログラムで関数を呼び出すと、例外が発生します。 System.InvalidOperationException:...多くのUIコンポーネントがこれを必要とするため、呼び出しスレッドはSTAでなければなりません。 スタックは、次のとおりです。
System.Windows.Input.InputManager..ctor()
System.Windows.Input.InputManager.GetCurrentInputManagerImpl()
ThisIsCalledByAnExternalProgram()
EDIT#3: 私は質問を読み違える - ... STAThread以内にフラグを立て...私は現在、これを試してみてくださいすることはできません。それが渡して動作しているとします - 私は呼び出し側のプログラムを制御できないので、これはまだ問題を解決しません。
EDIT#2: Win32フックを使用してください: 私は移植性のためにネット内にいたいです。すべてのグローバルフックの亜種は、最終的には仮想マシンの下のマシンに依存しています。私は用意されたC#のキーボードクラスを使いたいと思っています。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
//Requires WindowsBase.dll
//Requires PresentationCore.dll
namespace KeyBoardDemo
{
class Program
{
[STAThread]
static void Main(string[] args)
{
while (true)
{
if (Keyboard.IsKeyDown(Key.LeftAlt))
{
Console.WriteLine("LEFT ALT IS PRESSED");
}
else
{
Console.WriteLine("LEFT ALT IS NOT PRESSED");
}
}
}
}
}
(投票「をクローズ複製」再;私は同意、それは直接関係ありません) –
あなたはSTAThreadフラグを立てメソッド内ThisIsCalledByAnExternalProgramを()何を呼び出す発生したとき? –
http://stackoverflow.com/questions/7196883/capture-media-keys-when-application-is-minimized/7730869#7730869 –