internal void SetLocation(Form form, Control ctrl, Point point) { try { if (ctrl.InvokeRequired) { SetLocationCallback d = new SetLocationCallback(SetLocation); form.Invoke(d, new object[] { form, ctrl, point }); } else { ctrl.Location = point; } } catch (Exception e) { MessageBox.Show("# Error setLocation \n\n" + e); } }
/// <summary> /// Where to set the new location of the label /// </summary> /// <param name="newLocation">Location relative to window</param> private void SetLocation(Point newLocation) { if (label.InvokeRequired) { SetLocationCallback cb = new SetLocationCallback(SetLocation); Invoke(cb, new object[] { newLocation }); } else { label.Location = newLocation; label.Visible = true; } }
/// <summary> /// This method demonstrates a pattern for making thread-safe /// calls on a Windows Forms control. /// /// If the calling thread is different from the thread that /// created the UserControl object's, this method creates a /// SetLocationCallback and calls itself asynchronously using the /// Invoke method. /// /// If the calling thread is the same as the thread that created /// the UserControl object's, the Location property is set directly. /// </summary> /// <param name="obj">The UserControl object's</param> /// <param name="newLocation">Move object to this location</param> public void show(PictureBox obj, Point newLocation) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. try { #region Set Location in Safely if (obj.InvokeRequired) { SetLocationCallback d = new SetLocationCallback(show); obj.Invoke(d, new object[] { obj, newLocation }); } else { // if: // original location = newLocation = (50, 50) // obj.Size = (70, 70) // ---------------------------- // Virtual location in form // (15,15)._______ // |(50,50)| // 70| .---|---. Original location in form // | | | | // |___|___| | // | | // ._______. // <---> // 35 // // create virtual location from original location: obj.Location = new Point(newLocation.X - (obj.Size.Width / 2), newLocation.Y - (obj.Size.Height / 2)); } #endregion } catch { } }