gpt4 book ai didi

c# - Backgroundworker 打开主窗口拥有的第二个窗口

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:07 24 4
gpt4 key购买 nike

我面临这个问题:我有两个窗口(主窗口和自定义消息)。在我的代码中,我需要使用一个 backgroundworker。在 Dowork 方法中,我想打开与主窗口具有相同大小(宽度/高度)的第二个窗口(自定义消息)。因为我不知道主窗口的大小,所以我需要让第一个窗口拥有第二个窗口。那是我的代码:

    private void Starter_Click(object sender, RoutedEventArgs e)
{
string linkaddress = Address.Text;

BackgroundWorker CheckValidAddressBW = new BackgroundWorker();
CheckValidAddressBW.DoWork += CheckValidAddressBWDoWork;
CheckValidAddressBW.RunWorkerCompleted += CheckValidAddressBWComplete;
CheckValidAddressBW.RunWorkerAsync(linkaddress);
}

static void CheckValidAddressBWDoWork(object sender, DoWorkEventArgs e)
{
string bandaddress =""+ e.Argument;
bool isValid = false;
/* STUFF INSIDE */
e.Result = isValid;
}
static void CheckValidAddressBWComplete(object sender, RunWorkerCompletedEventArgs e)
{
bool result =(bool) e.Result;
if(result==false)
{
CustomMessage cm = new CustomMessage ();
cm.Width = 800;
cm.Height = 600;
cm.Show();
}
}

所以在这段代码中我想做的是这样的:

        if(result==false)
{
CustomMessage cm = new CustomMessage {Owner=this}; //WHERE this means the mainwindow
cm.Width = this.ActualWidth;
cm.Height = this.ActualHeight;
cm.Show();
}

因为我使用的是后台 worker ,所以我不能使用“this”这个词。所以我想知道是否有办法做到这一点。提前谢谢你。

注意我希望我的问题很清楚:)

最佳答案

我认为您需要将主窗口对象作为 BackgroundWorker 的参数之一传递。这里我以 Tuple 对象为例,但您可能需要创建更合适的类对象:

private void Starter_Click(object sender, RoutedEventArgs e)
{
var linkaddress = Address.Text;

BackgroundWorker CheckValidAddressBW = new BackgroundWorker();
CheckValidAddressBW.DoWork += CheckValidAddressBWDoWork;
CheckValidAddressBW.RunWorkerCompleted += CheckValidAddressBWComplete;
CheckValidAddressBW.RunWorkerAsync(Tuple.Create<string, Window>(linkaddress, this));
}
static void CheckValidAddressBWDoWork(object sender, DoWorkEventArgs e)
{
Tuple<string, Window> args = e.Argument as Tuple<string, Window>;
string bandaddress = args.Item1;
bool isValid = false;
/* STUFF INSIDE */
e.Result = Tuple.Create<bool, Window>(isValid, args.Item2);
}
static void CheckValidAddressBWComplete(object sender, RunWorkerCompletedEventArgs e)
{
Tuple<bool, Window> args = e.Result as Tuple<bool, Window>;
bool result = args.Item1;
if (result == false)
{
CustomMessage cm = new CustomMessage { Owner = args.Item2 };
cm.Width = 800;
cm.Height = 600;
cm.Show();
}
}

关于c# - Backgroundworker 打开主窗口拥有的第二个窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25749740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com