GSI

'invoke'에 해당되는 글 1건

  1. 2009.12.15 C# Thread, delegate, Invoke 사용예


    public partial class ucPanel : UserControl
    {
        public ucPanel()
        {
            InitializeComponent();

            //
            backgroundWorker1.RunWorkerAsync();
        }

        static public Font ChangeFontSize2(Font font, float fontSize, GraphicsUnit unit)
        {
            if (font != null)
            {
                float currentSize = font.Size;
                if (currentSize != fontSize)
                {
                    font = new Font(font.Name, fontSize,
                        font.Style, unit,
                        font.GdiCharSet, font.GdiVerticalFont);
                }
            }
            return font;
        }

        public delegate void OnAddNode(string title, int x, int y);
        public void AddNode(string title, int x, int y)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new OnAddNode(this.AddNode), new object[] { title, x, y });
                return;
            }

            // 객체 추가
            Label lbl2 = new Label();
            lbl2.AutoSize = true;
            lbl2.Text = title;
            lbl2.Font = ChangeFontSize2(lbl2.Font, lbl2.Font.Size * 2, GraphicsUnit.Pixel);
            lbl2.Left = x;
            lbl2.Top = y;
            this.Controls.Add(lbl2);

            ucNode ucn = new ucNode();
            ucn.Left = x;
            ucn.Top = y;
            this.Controls.Add(ucn);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int breakCount = 0;
            Random rand = new Random();

            while (true)
            {
                //
                this.Invoke(new OnAddNode(this.AddNode), new object[] { "test", rand.Next(10, 738), rand.Next(10, 460) });

                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));

                //
                breakCount++;
                if (breakCount > 100)
                {
                    break;
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }
    }

Posted by gsi
: