【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)
posted @ 2019-07-02 09:47  【唐】三三  阅读(856)  评论(0编辑  收藏  举报