学习delphi的命名管道通讯,写了一个很简单的程序,可是却有问题啊;首先在form1上放置两个按钮button1和button2,再放置两个edit1和edit2控件;
现在想通过button1的点击事件建立一个命名管道,然后把edit1的内容写入管道里面;
按钮2的点击事件访问这个命名管道,读取管道里面的内容,把读到的内容写入edit2里面;按钮1的点击事件:
var
dwTO,dwRead,dwWritten:DWORD;
hSvr:Thandle; bRead:Byte; w:string; //写入字符
begin
dwTO := NMPWAIT_USE_DEFAULT_WAIT; hSvr:=CreateNamedPipe(('\\.\PIPE\test_pipe'),PIPE_ACCESS_DUPLEX,PIPE_TYPE_BYTE,3,256,256,dwTO,nil);
if( hSvr =INVALID_HANDLE_VALUE ) then
showmessage('Invalid handle')
else
begin
dwWritten:=0;
w:=self.Edit1.Text;
showmessage(w);
WriteFile(hSvr,w,length(w)*sizeof(char),dwWritten,nil); showmessage('have written: '+inttostr(dwWritten)+'lasterror:'+inttostr(getlasterror())); end;end;
按钮2的点击事件:procedure TForm1.Button2Click(Sender: TObject);
var
hClient:Thandle;
dwRead,dwWritten:DWORD;
r:string;
begin
hClient:=CreateFile(Pchar('\\.\PIPE\test_pipe'),GENERIC_WRITE or GENERIC_READ,0,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if(hClient = INVALID_HANDLE_VALUE) then
showmessage('hClient is invalid')
else
begin
ReadFile(hClient,r[1],length(self.Edit1.Text),dwRead,nil);
self.Edit2.Text:=r;
end;end;
然后运行程序;
点击按钮1,在showmessage('have written: '+inttostr(dwWritten)+'lasterror:'+inttostr(getlasterror()))的时候出现getlasterror的值为536,而dwwritten的值为0,说明没有写入管道里面,所以即使去点击按钮2,也是无法接收数据的了;
请问按钮1为什么在writefile的时候为什么会出现536的错误啊??
现在想通过button1的点击事件建立一个命名管道,然后把edit1的内容写入管道里面;
按钮2的点击事件访问这个命名管道,读取管道里面的内容,把读到的内容写入edit2里面;按钮1的点击事件:
var
dwTO,dwRead,dwWritten:DWORD;
hSvr:Thandle; bRead:Byte; w:string; //写入字符
begin
dwTO := NMPWAIT_USE_DEFAULT_WAIT; hSvr:=CreateNamedPipe(('\\.\PIPE\test_pipe'),PIPE_ACCESS_DUPLEX,PIPE_TYPE_BYTE,3,256,256,dwTO,nil);
if( hSvr =INVALID_HANDLE_VALUE ) then
showmessage('Invalid handle')
else
begin
dwWritten:=0;
w:=self.Edit1.Text;
showmessage(w);
WriteFile(hSvr,w,length(w)*sizeof(char),dwWritten,nil); showmessage('have written: '+inttostr(dwWritten)+'lasterror:'+inttostr(getlasterror())); end;end;
按钮2的点击事件:procedure TForm1.Button2Click(Sender: TObject);
var
hClient:Thandle;
dwRead,dwWritten:DWORD;
r:string;
begin
hClient:=CreateFile(Pchar('\\.\PIPE\test_pipe'),GENERIC_WRITE or GENERIC_READ,0,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if(hClient = INVALID_HANDLE_VALUE) then
showmessage('hClient is invalid')
else
begin
ReadFile(hClient,r[1],length(self.Edit1.Text),dwRead,nil);
self.Edit2.Text:=r;
end;end;
然后运行程序;
点击按钮1,在showmessage('have written: '+inttostr(dwWritten)+'lasterror:'+inttostr(getlasterror()))的时候出现getlasterror的值为536,而dwwritten的值为0,说明没有写入管道里面,所以即使去点击按钮2,也是无法接收数据的了;
请问按钮1为什么在writefile的时候为什么会出现536的错误啊??
LPCVOID lpBuffer, // pointer to data to write to file
DWORD nNumberOfBytesToWrite, // number of bytes to write
LPDWORD lpNumberOfBytesWritten, // pointer to number of bytes written
LPOVERLAPPED lpOverlapped // pointer to structure needed for overlapped I/O
);
// WriteFile(hSvr,w,length(w)*sizeof(char),dwWritten,nil);
WriteFile(hSvr,PChar(w),length(w),dwWritten,nil);