4

SendKeys.Sendに奇妙な問題があります

基本的に何が起こるかはこれです。google.comでInternetExplorerに焦点を合わせており、SendKeys.Send( "TestSample \ n");を呼び出しています。予測できない方法でいくつかのキー(TeestSampleやTestSSSampleなど)を2回送信することがあります。それは約20%の確率で起こります。

また、文字列SendKeys.Send( "Test Sample \ n")にスペースを含めると、1つのポイントを除いて同様に予測できません。これを行うたびに、テストサンプルに入り、グーグル検索を行いますが、テキストを入力した後にスペースバーを押したので、結果ページも下にスクロールします。

他の誰かがこの振る舞いを見たことがありますか。メモ帳にフォーカスがある場合、このように機能するようには見えません。

(ここにいくつかのサンプルコードを示します。これをフォームの1秒タイマーに入れ、DllImport定義をクラスの最上位近くに配置します。)このアプリケーションは、Internet Explorer(8.0)上のGoogle.comで約20%の確率で失敗します。 )。

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();

    private void timer1_Tick(object sender, EventArgs e)
    {
        IntPtr foreground = GetForegroundWindow();
        if (foreground != _currentForeground)
        {
            _currentForeground = foreground;
            var titleBuilder = new StringBuilder(200);
            GetWindowText(foreground, titleBuilder, 200);
            string title = titleBuilder.ToString();
            Debug.WriteLine("Title of " + title);
            if (title == "Google - Windows Internet Explorer")
            {
                Debug.WriteLine("Sending keys");
                SendKeys.Send("Test Sample\n");
            }
            if (title == "Untitled - Notepad")
                SendKeys.Send("Test notpad sample\n");
            Thread.Sleep(2000);
        }
    }
    private IntPtr _currentForeground = IntPtr.Zero;
4

1 に答える 1

-1

新しいデータを書き込みたいhWndを見つけて、SetWindowTextWを呼び出す方がよい場合があります。

[DllImport( "user32.dll" )]
public static extern int SetWindowTextW( HandleRef hWnd, [MarshalAs( UnmanagedType.LPWStr )] string text );

その後、ボタンのhWndを見つけて、WM_LBUTTONDOWNとWM_LBUTTONUPを使用して送信します。

[DllImport( "user32.dll" )]
public static extern int PostMessage( HandleRef hWnd, WM msg, int wParam, int lParam );

    WM_LBUTTONDOWN = 0x0201
    WM_LBUTTONUP = 0x0202
于 2010-02-22T23:55:02.593 に答える