Author Topic: Creating new layer with plot styles  (Read 11053 times)

0 Members and 1 Guest are viewing this topic.

It's Alive!

  • Retired
  • Needs a day job
  • Posts: 8702
  • AKA Daniel
Re: Creating new layer with plot styles
« Reply #15 on: February 28, 2008, 07:42:26 AM »
Try this  :-o

Code: [Select]
//Hi Kerry :)
using AcAp = Autodesk.AutoCAD.ApplicationServices;
using AcEd = Autodesk.AutoCAD.EditorInput;
using AcGe = Autodesk.AutoCAD.Geometry;
using AcRx = Autodesk.AutoCAD.Runtime;
using AcDb = Autodesk.AutoCAD.DatabaseServices;
using AcWd = Autodesk.AutoCAD.Windows;
#endregion

[assembly: CommandClass(typeof(ExecMethod.Commands))]

namespace ExecMethod
{
  public class Commands
  {
    public ObjectId CreateLayer(string layerName, short layerColor, LineWeight lineweightName)
    {
      Editor ed = AcAp.Application.DocumentManager.MdiActiveDocument.Editor;
      ObjectId layerId = ObjectId.Null;
      Database db = HostApplicationServices.WorkingDatabase;

      using (Transaction tr = db.TransactionManager.StartTransaction())
      {
        LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForWrite);
        if (lt.Has(layerName))
        {
          layerId = lt[layerName];
          if (layerId.IsErased)
          {
            LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForWrite, true);
            ltr.Erase(false);
            layerId = ltr.Id;
          }
        }
        else
        {
          if (layerColor > 255)
          {
            ed.WriteMessage(string.Format(" ERROR: Could not use LayerColor \"{0}\", using 0 instead.", layerColor));
            layerColor = 0;
          }
          LayerTableRecord ltr = new LayerTableRecord();
          ltr.Name = layerName;
          ltr.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, layerColor);
          ltr.LineWeight = lineweightName;
          layerId = lt.Add(ltr);
          tr.AddNewlyCreatedDBObject(ltr, true);
        }
        tr.Commit();
      }
      return layerId;
    }

    //
    public void AddPlotStyle(string PlotStyleName)
    {
      Database db = AcAp.Application.DocumentManager.MdiActiveDocument.Database;
      if (db.PlotStyleMode == false)
      {
        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
          using (PlaceHolder hldr = new PlaceHolder())
          {
            DictionaryWithDefaultDictionary d =
              (DictionaryWithDefaultDictionary)tr.GetObject
                  (db.PlotStyleNameDictionaryId, OpenMode.ForWrite);
            d.SetAt(PlotStyleName, hldr);
            tr.Commit();
          }
        }
      }
    }

    //
    public void AddPlotStyleToLayer(ObjectId id, string PlotStyleName)
    {
      Database db = AcAp.Application.DocumentManager.MdiActiveDocument.Database;
      if (db.PlotStyleMode == false)
      {
        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
          DictionaryWithDefaultDictionary d =
            (DictionaryWithDefaultDictionary)tr.GetObject
                (db.PlotStyleNameDictionaryId, OpenMode.ForRead);

          LayerTableRecord ltr =
               (LayerTableRecord)tr.GetObject(id, OpenMode.ForWrite);
          ltr.PlotStyleNameId = d.GetAt(PlotStyleName);
          tr.Commit();
        }
      }
    }

    [CommandMethod("doit")]
    public void doit()
    {
      Editor ed = AcAp.Application.DocumentManager.MdiActiveDocument.Editor;
      try
      {
        string plotstyle = "Style 1";
        AddPlotStyle(plotstyle);
        ObjectId id = this.CreateLayer("Daniel", 7, LineWeight.ByLayer);
        AddPlotStyleToLayer(id, plotstyle);
      }
      catch (System.Exception ex)
      {
        ed.WriteMessage("\n" + ex.Message + "\n" + ex.StackTrace);
      }
    }
  }
}
« Last Edit: February 28, 2008, 08:53:51 AM by Daniel »

It's Alive!

  • Retired
  • Needs a day job
  • Posts: 8702
  • AKA Daniel
Re: Creating new layer with plot styles
« Reply #16 on: February 28, 2008, 07:44:59 AM »

mcarson

  • Guest
Re: Creating new layer with plot styles
« Reply #17 on: February 28, 2008, 10:11:12 AM »
Excellent! :-D

What you have provided works in itself. I now have to build it into my program.

Thanks very much!

Bryco

  • Water Moccasin
  • Posts: 1883
Re: Creating new layer with plot styles
« Reply #18 on: February 28, 2008, 10:21:31 AM »
PlaceHolder hldr, that's a pretty cool find Daniel, this C# stuff doesn't seem to get any easier. I used to think the vba help files were bad but compared to C# they are amazing.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Creating new layer with plot styles
« Reply #19 on: February 28, 2008, 02:53:29 PM »

well researched Daniel !
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

It's Alive!

  • Retired
  • Needs a day job
  • Posts: 8702
  • AKA Daniel
Re: Creating new layer with plot styles
« Reply #20 on: February 28, 2008, 10:32:37 PM »
Excellent! :-D

What you have provided works in itself. I now have to build it into my program.

Thanks very much!

You’re welcome, I must admit I probably would never had got this one if it wasn’t for Art Cooney’s post. 

mcarson

  • Guest
Re: Creating new layer with plot styles
« Reply #21 on: February 29, 2008, 05:25:49 AM »
Another can of worms...

Attempt to add the layer more than once, and have a look at the ACAD layer dialog each time
The plot style name does not stay assigned to the layer, instead it moves with each new layer.

Am I getting this all wrong?



It's Alive!

  • Retired
  • Needs a day job
  • Posts: 8702
  • AKA Daniel
Re: Creating new layer with plot styles
« Reply #22 on: February 29, 2008, 05:55:54 AM »
you might try testing if the style exists ie

Code: [Select]
public void AddPlotStyle(string PlotStyleName)
    {
      Database db = AcAp.Application.DocumentManager.MdiActiveDocument.Database;
      if (db.PlotStyleMode == false)
      {
        using (Transaction tr = db.TransactionManager.StartTransaction())
        {
          using (PlaceHolder hldr = new PlaceHolder())
          {
            DictionaryWithDefaultDictionary d =
              (DictionaryWithDefaultDictionary)tr.GetObject
                  (db.PlotStyleNameDictionaryId, OpenMode.ForWrite);

            if (!d.Contains(PlotStyleName))//added
              d.SetAt(PlotStyleName, hldr);

            tr.Commit();
          }
        }
      }
    }
« Last Edit: February 29, 2008, 07:45:40 AM by Daniel »

mcarson

  • Guest
Re: Creating new layer with plot styles
« Reply #23 on: February 29, 2008, 05:59:01 AM »
I just done that while waiting on a reply; you're faster than I am!

Works now!

Thanks again!

I'll post my full code over the weekend

It's Alive!

  • Retired
  • Needs a day job
  • Posts: 8702
  • AKA Daniel
Re: Creating new layer with plot styles
« Reply #24 on: February 29, 2008, 07:49:44 AM »
Good deal!, usually the code I post is rough draft,  :-o
you should probably add your error checking, try catches etc.,
and maybe even pass the working database as a parameter.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Creating new layer with plot styles
« Reply #25 on: February 29, 2008, 06:00:37 PM »
Quote from: Dan
Latitude 22°17'33.02"N  Longitude 113°57'1.73"E

Dan, what's your Vertitude ?

;-)
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: Creating new layer with plot styles
« Reply #26 on: February 29, 2008, 06:09:24 PM »
Dan, what's your Vertitude ?

Kinda personal dontcha think?

 :lol:
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

It's Alive!

  • Retired
  • Needs a day job
  • Posts: 8702
  • AKA Daniel
Re: Creating new layer with plot styles
« Reply #27 on: March 02, 2008, 06:43:49 AM »
Quote from: Dan
Latitude 22°17'33.02"N  Longitude 113°57'1.73"E

Dan, what's your Vertitude ?

;-)

33rd floor, maybe 100 or so meters MSL

PS. If you visit, bring black licorice  :laugh:
« Last Edit: March 02, 2008, 07:02:14 AM by Daniel »

stevenh0616

  • Guest
Re: Creating new layer with plot styles
« Reply #28 on: October 18, 2012, 02:52:39 PM »
Thanks everyone for this great set of posts... this all worked really well as I encountered the same issues.

I think I saw someone ask about checking if the drawing uses CTBs or STBs. Here is some code to do just that, and it works well. Basically it just checks the system variable PSTYLEMODE and returns a boolean value, so if it's style mode, then you can apply the plot style to the layers.

Code - vb.net: [Select]
  1. Public Shared Function GetPlotStyleModeTrueColorFalseStyle() As Boolean
  2.         Dim result As Boolean = False
  3.         If Convert.ToInt32(Application.GetSystemVariable("pstylemode")) = 1 Then
  4.             result = True
  5.         End If
  6.         Return result
  7.     End Function