using System;
using System.Windows.Forms;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using AcRx = Autodesk.AutoCAD.Runtime;
using AcAp = Autodesk.AutoCAD.ApplicationServices;
using AcDb = Autodesk.AutoCAD.DatabaseServices;
using AcGe = Autodesk.AutoCAD.Geometry;
using AcEd = Autodesk.AutoCAD.EditorInput;
 
[assembly: AcRx.CommandClass(typeof(AddWithTimer.MyCommands))]
 
namespace AddWithTimer
{
  public class MyCommands
  {
    // Интервал между вызовами таймера
    const int tm_interval = 1000;
    // Таймер
    static Timer tm = null;
    // Параметры окружности: радиус и цвет
    static double c_radius = 0;
    static int c_color = 0;
    // Случайные числа для цвета и радиуса
    static Random r_color = new Random();
    static Random r_radius = new Random();
    static AcGe.Point3d c_center;
 
    static Control syncCtrl = null;
 
    static MyCommands()
    {
      syncCtrl = new Control();
      syncCtrl.CreateControl();
    }
    ~MyCommands()
    {
      if (tm != null)
      {
        tm.Enabled = false; tm.Stop(); tm.Dispose(); tm = null;
      }
    }
 
    private static void TimerEventProc(object obj, EventArgs myEventArgs)
    {
        tm.Enabled = false; // Приостанавливаем таймер
        c_color = r_color.Next(255); // Цвет окружности от 0 до 255
        c_radius = r_radius.NextDouble();
        c_radius *= 100; // Радиус окружности в пределах от 0 до 100.
        double x_circle = r_radius.NextDouble();
        double y_circle = r_radius.NextDouble();
        c_center = new AcGe.Point3d(x_circle * 1000, y_circle * 1000, 0);
        BackgroundProcess();
        tm.Enabled = true; // Отпускаем таймер
    }
 
    delegate void FinishedProcessingDelegate();
 
    /// <summary>
    /// Функция, которая непосредственно работает с чертежом
    /// </summary>
    static void FinishedProcessing()
    {
      AcAp.Document doc = AcAp.Application.DocumentManager.MdiActiveDocument;
      using (AcAp.DocumentLock locDoc = doc.LockDocument())
      {
        AcDb.ObjectId spaceId = doc.Database.CurrentSpaceId;
        using (AcDb.BlockTableRecord btr = spaceId.Open(AcDb.OpenMode.ForWrite) as AcDb.BlockTableRecord)
        {
          using (AcDb.Circle circ = new AcDb.Circle(c_center, AcGe.Vector3d.ZAxis, c_radius))
          {
            circ.SetDatabaseDefaults();
            circ.ColorIndex = c_color;
            btr.AppendEntity(circ);
          }
        }
      }
    }
    /// <summary>
    /// Функция, которая выполняется из таймера
    /// </summary>
    static void BackgroundProcess()
    {
      if (syncCtrl.InvokeRequired)
        syncCtrl.Invoke(
          new FinishedProcessingDelegate(FinishedProcessing));
      else
        FinishedProcessing();
    }
 
    [AcRx.CommandMethod("TimerStart")]
    public void TimerStart()
    {
      if (tm != null)
      {
        tm.Enabled = false; tm.Stop(); tm.Dispose();
      }
      tm = new Timer();
      tm.Interval = tm_interval; // Задаем интервал
      tm.Tick += new EventHandler(TimerEventProc);
      tm.Enabled = true;
      tm.Start();
    }
 
    [AcRx.CommandMethod("TimerStop")]
    public void TimerStop()
    {
      if (tm != null)
      {
        tm.Enabled = false; tm.Stop(); tm.Dispose(); tm = null;
      }
    }
  }
}