老问题,最近做了一个自定义词组程序为的是自动向某个输入框发送字符串,其中
的核心函数是取得当前鼠标下的窗口句柄后向该窗口中拥有焦点的输入栏发送中文或
西文字符,在记事本下发送中文或西文均正常,但向IE,Word,Excel等发送
西文正常而中文却出现乱码,打开输入法后发送又正常了,不知是什么问题,
怎么解决?废话少说,不欢迎灌水!请发修改后的源程序,本人调试成功后立
即给分!!!!!!!
--------------第一种方法------------
这种方法在中文输入法打开的情况下中西文都正常,
但我不想用这种费事的办法.
------------------------------------
//模拟按键函数
procedure TForm1.SendKeys(sSend:string);
var
i:integer;
Sstr:string;
focushld,windowhld:hwnd;
threadld:dword;
ch: byte;
begin
windowhld:=GetForegroundWindow;
threadld:=GetWindowThreadProcessId(Windowhld,nil);
AttachThreadInput(GetCurrentThreadId,threadld,true);
Focushld:=getfocus;
getcursorpos(p); //查鼠标坐标
Focushld:=WindowFromPoint(p); //返回句柄
AttachThreadInput(GetCurrentThreadId,threadld,false);
if (focushld=0) or
(focushld=Self.Memo1.Handle) or
(focushld=Self.Edit1.Handle) or
(focushld=Self.Edit2.Handle) or
(focushld=SpinEdit1.Handle) then
begin
Exit;
end;
i := 1;
while i <= Length(sSend) do
begin
ch := byte(sSend[i]);
if Windows.IsDBCSLeadByte(ch) then
begin
Inc(i);
SendMessage(focushld, WM_IME_CHAR, MakeWord(byte(sSend[i]), ch), 0);
end
else
begin
SendMessage(focushld, WM_IME_CHAR, word(ch), 0);
end;
Inc(i);
end;
SendMessage(focushld, WM_IME_CHAR, word(13), 0);
end;
//定时器定时发送字符
procedure TForm1.Timer1Timer(Sender: TObject);
begin
SendKeys('ABCD1234大话西游');
end;
--------------第二种方法------------
这种方法用拷贝-粘贴的方式,在记事本下正常,
但在WORD下毫无反应!
------------------------------------
procedure TGoodDictForm.SendKey();
var
i:integer;
focushld,windowhld:hwnd;
threadld:dword;
ch: byte;
begin
windowhld:=GetForegroundWindow;
threadld:=GetWindowThreadProcessId(Windowhld,nil);
AttachThreadInput(GetCurrentThreadId,threadld,true);
getcursorpos(p); //查鼠标坐标
Focushld:=WindowFromPoint(p); //返回句柄
AttachThreadInput(GetCurrentThreadId,threadld,false);
if (focushld=0) or (focushld=Self.Memo1.Handle) then
begin
Exit;
end;
SendMessage(focushld, WM_Paste, 0, 0);
end;
//定时器定时发送字符
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Edit1.SelectAll;
Edit1.CopyToClipboard;
SendKeys();
end;
To kingkong
要正確送出中文字符一定要依照微軟的IME機制, 單純用SendMessage
是不能夠的. 你可以把要送出的字符放在剪貼板中, 使用keybd_event
這個API送出 Ctrl 與 V 兩鍵的組合. 就能夠把中英文字串放到Word
等軟件中,
keybd_event(VK_CONTROL, 0, 0, 0);
keybd_event(Ord('v'), 0, 0, 0);
keybd_event(Ord('v'), 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);
uses sendkey32
{+ = Shift
^ = Control
% = Alt}
SendKeys('^X',true);
发送 Control+X消息