動作環境
Windows 8.1 Pro (64bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2
c++ builder > ソフト操作 > notepad を開いて、ステータスバーを表示 / 非表示 > Alt+V, S の送信
をWPFで実装してみる。
参考
キーボードシミュレータを作ってみよう!! by INASOFTさん
keybd_event()のDllImportと使用例が参考になりました。
情報感謝です。
Visual Studio | WPF > Window Message の送受信
FindWindow()関連
Visual Studio | WPF > ソフト操作 > Explorerを起動する > ShellExecute()でなくProcess.Start()を使う方法
外部ソフトの起動の仕方。
code
MainWindow.xaml
<Window x:Class="_171115_t1112_notepadKey.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:_171115_t1112_notepadKey"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Name="B_notepad" Content="Open Notepad" Height="30" Click="B_notepad_Click"/>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
// 以下を追加
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Threading;
namespace _171115_t1112_notepadKey
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, String lpWindowName);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern uint keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
static readonly byte VK_MENU = 0x12;
static readonly byte KEYEVENTF_KEYUP = 0x0002;
public MainWindow()
{
InitializeComponent();
}
private void openSoftware(string softPath, string argument)
{
var psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = softPath;
psi.Arguments = argument;
psi.UseShellExecute = true;
psi.CreateNoWindow = true;
var proc = System.Diagnostics.Process.Start(psi);
}
private void onOffStatusbar()
{
IntPtr win = FindWindow(null, "無題 - メモ帳");
SetForegroundWindow(win);
for(int loop=0; loop<3; loop++)
{
Thread.Sleep(3000); // msec
keybd_event(VK_MENU, 0, 0, (UIntPtr)0); // Altキー
keybd_event((byte)'V', 0, 0, (UIntPtr)0);
keybd_event((byte)'S', 0, 0, (UIntPtr)0);
keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, (UIntPtr)0); // これがないとAltを押したままになる
}
}
private void B_notepad_Click(object sender, RoutedEventArgs e)
{
openSoftware("notepad.exe", "");
onOffStatusbar();
}
}
}
ボタンを押すとNotepadが起動して、ステータスバーの表示、非表示が行われる。
(その間は他のソフトを使わなこと)
備考
keybd_event
Windows NT/2000:この関数は、SendInput 関数に取って代わられています。この関数の代わりに SendInput を使ってください。