从另一个进程更新TextBox文本 [英] Updating TextBox text from another process
问题描述
我有两个WinForms应用程序,我需要从Application2向Application1中的TextBox添加文本.我已经使用命名管道和WCF成功完成了此操作.我可以成功地从Application2调用Application1中的方法,但是我收到" Invoke或BeginInvoke不能在控件上调用,直到创建了窗口句柄."错误或文本框未更新为全部.
I have two WinForms applications and I need to add text to TextBox in Application1 from Application2. I've successfully done this using named pipes and WCF. I can successfuly call a method in Application1 from Application2 but I'm getting either "Invoke or BeginInvoke cannot be called on a control until the window handle has been created." error or the textbox is not updated at all.
这是我的基本代码. GetMessage
由Application2调用.这个根本不会更新TextBox:
Here's my basic code. GetMessage
is called by Application2. This one doesn't update TextBox at all:
public void GetMessage(string msg)
{
UpdateTextbox(msg);
}
private void UpdateTextbox(string msg)
{
this.textBox1.Text += msg + Environment.NewLine;
}
这引发了Invoke错误:
This one throws Invoke error:
public void GetMessage(string msg)
{
Action a = () => UpdateTextbox(msg);
textBox1.BeginInvoke(a);
}
我试图通过强制创建句柄来欺骗自己的方式,但是它也不会更新TextBox:
I tried to cheat my way by forcing creation of the handle with this, but it doesn't update TextBox either:
public void GetMessage(string msg)
{
IntPtr handle = textBox1.Handle;
Action a = () => UpdateTextbox(msg);
textBox1.BeginInvoke(a);
}
我该怎么办?
推荐答案
由于问题在于Form1的文本框位于Form1的另一个实例上.从 Application1.Form1
中观察以下代码,该代码将启动命名管道服务:
The problem is that the TextBox of the Form1 was on another instance of the Form1. Observe this code from Application1.Form1
which starts the named pipe service:
private void Form1_Load(object sender, EventArgs e)
{
ServiceHost host = new ServiceHost(typeof(Form1), new Uri[] { new Uri("net.pipe://localhost") });
host.AddServiceEndpoint(typeof(ISmsService), new NetNamedPipeBinding(), "PipeReverse");
host.Open();
}
如果我理解正确,这将启动 Form1
的实例.因此,当Application2调用 Application1.GetMessage
时,它将调用 ServiceHost-instance-Form1.GetMessage
.
If I am understanding it right, this starts an instance of Form1
. Thus, when Application2 calls Application1.GetMessage
, it calls ServiceHost-instance-Form1.GetMessage
.
要访问 Form1
的主实例,我将代码更改为:
To access main instance of Form1
I changed my code to this:
public Form1()
{
InitializeComponent();
if (mainForm == null)
{
mainForm = this;
}
}
private static Form1 mainForm;
public static Form1 MainForm
{
get
{
return mainForm;
}
}
private void UpdateTextbox(string msg)
{
MainForm.textBox1.Text += msg + Environment.NewLine;
}
现在可以正常工作了.
这篇关于从另一个进程更新TextBox文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!