【winform】主窗体多线程给子窗体传值


参考:C# winform窗体间传值(使用委托或事件)

0.委托窗体传值#

1.主窗体多线程给子窗体传值(多线程)#

解决方案:主要使用委托,因为会出现跨线程错误
主窗体

        public FormMain()
        {
            InitializeComponent();

            //background thread running
            Action sAction = async () => await CallbackWorkItem();
            System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Run(sAction);
            System.Threading.Tasks.Task.WaitAll(task);
        }




        private async Task CallbackWorkItem()
        {
            List<string> filesGuidList = new List<string>(); //the GUID to download
           

            while (true)
            {
                try
                {
                     int count = int.Parse(COUNT);

                    if (string.IsNullOrWhiteSpace(DOWNPATH))
                    {
                        MessageBox.Show("the config's key for DOWNPATH is empty.");
                        return;
                    }

                    if (!string.IsNullOrWhiteSpace(PROJECTID) && !string.IsNullOrWhiteSpace(HOID))
                    {
                        filesGuidList.Clear();

                        //1.Check
                        bool checkTask = await CheckIds(Guid.Parse(PROJECTID), Guid.Parse(HOID));

                        if (checkTask)
                        {
                            deliveryFile.SetMonitor(deliveryFile,"download begins.", COUNT);
                            //2.Load
                            var files = await LoadDeliveryFiles(Guid.Parse(PROJECTID), Guid.Parse(HOID), TEMPKEY, count);

                            if (count == 1)
                            {
                                deliveryFile.SetMonitor(deliveryFile,$"download the data: {files[0].Name}", COUNT);
                            }
                            else
                            {
                                deliveryFile.SetMonitor(deliveryFile,$"download the {COUNT} data.", COUNT);
                            }


                            foreach (var file in files)
                            {
                                filesGuidList.Add(file.Guid.ToString());
                            }


                            string fileZipName = string.Empty;
                            //3.download
                            if (DownloadFile(Guid.Parse(PROJECTID), filesGuidList, out fileZipName))
                            {
                                DeleteRedis(Guid.Parse(PROJECTID), filesGuidList, fileZipName, TEMPKEY);
                                deliveryFile.SetMonitor(deliveryFile,"end of download.", COUNT);
                            }
                        }
                        else
                        {
                            deliveryFile.SetMonitor(deliveryFile,"no download data.", COUNT);
                           await Task.Delay(1000);
                        }
                    }
                    deliveryFile.SetMonitor(deliveryFile,"rest 7 seconds...", COUNT);

                    await Task.Delay(7000);

                }
                catch (FormatException e)
                {
                    MessageBox.Show("the config's key for PROJECTID or HOID must be GUID,and COUNT must be number.");
                    await Task.Delay(60000); //if throw exception,re-execute after 60 seconds
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    await Task.Delay(60000); //if throw exception,re-execute after 60 seconds
                }
            }
        }

FileDeliveryFile.cs

public partial class FormDeliveryFile : Form
{
	public delegate void FileUpdateStatus(Control control, string monitor, string count);
}

public void SetMonitor(Control control, string monitor, string count)
        {

            if (control.InvokeRequired)
            {
                //direct access to controls across threads-跨线程直接访问控件 - InvokeRequired
                FileUpdateStatus update = new FileUpdateStatus(SetMonitor);
                control.Invoke(update, new object[] { control, monitor, count });


            }
            else
            {
                this.txtMonitor.Text = monitor;
                this.txtMonitorSetCount.Text = count;
                this.txtMonitor.ForeColor = Color.Brown;
                this.txtMonitorSetCount.ForeColor = Color.Brown;


                this.dataGridView1.DataSource = LoadPath();
                this.dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;  //自适应列宽
                this.dataGridView1.Columns[1].DefaultCellStyle = new DataGridViewCellStyle() { ForeColor = Color.Blue, Font = new Font("Arial", 11F) }; //样式
                this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                this.dataGridView1.ReadOnly = true;
                if (this.dataGridView1.FirstDisplayedScrollingRowIndex > -1)
                {
                    this.dataGridView1.FirstDisplayedScrollingRowIndex = VerticalScrollIndex;//设置垂直滚动条位置
//                    this.dataGridView1.CurrentCell = this.dataGridView1.Rows[rowIndex].Cells[0];
                }
            }

        }

2.datagridview 滚动时位置不变#

if (this.dataGridView1.FirstDisplayedScrollingRowIndex > -1)
                {
                    this.dataGridView1.FirstDisplayedScrollingRowIndex = VerticalScrollIndex;//设置垂直滚动条位置
                    this.dataGridView1.CurrentCell = this.dataGridView1.Rows[rowIndex].Cells[0];
                }

Scroll事件

 private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
        {
            try
            {
                if (e.ScrollOrientation == ScrollOrientation.VerticalScroll)
                {
                    VerticalScrollIndex = e.NewValue;
                }
                else if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
                {
                    HorizontalOffset = e.NewValue;
                }

            }
            catch { }
        }

3.datagridview 第1列点击打开文件并选择文件夹位置#

		private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
			//第1列
            if (e.ColumnIndex == 1)
            {
                string file = DOWNPATH + this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                System.Diagnostics.Process.Start(file); //打开文件
                //string v_OpenFolderPath = DOWNPATH; 
                System.Diagnostics.Process.Start("explorer.exe", "/select," + file); //打开后选择文件
                //this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());

            }
        }

4.鼠标移动到文字上显示"hand"按钮#

      private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
        {

            this.Cursor = Cursors.Default;
        }

        private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                this.Cursor = Cursors.Hand;
            }
        }

5.安全性问题,System.UnauthorizedAccessException异常#

Advanced Installer打包Winform后安装在C盘权限不足的解决方法

解决方法:

(1)VS中右键项目=》属性=》安全性,勾选【启用ClickOne安全设置】;

(2)找到app.manifest,将

修改为 (3)再次找到项目属性的安全性,去掉【启用ClickOne安全设置】的勾选; ![](https://img2018.cnblogs.com/blog/196558/201907/196558-20190705150713123-2038560278.png)

作者:【唐】三三

出处:https://www.cnblogs.com/tangge/p/11118631.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   【唐】三三  阅读(858)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示