Code posted a long time ago in the missing jprdintprev.
I don't know if it is exactly what you want but it is a starting point.
I also didn't test it due to lack of time.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Customization;
using Autodesk.AutoCAD.Geometry;
using System.IO;
using System.Runtime.InteropServices;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
namespace CUISAMP_2010
{
public class CuiSamp
{
// All Cui files (main/partial/enterprise) have to be loaded into an object of class
// CustomizationSection
// cs - main AutoCAD CUI file
CustomizationSection cs;
CustomizationSection entCs;
CustomizationSection[] partials;
//This bool is used to determine when to save the cui
//If running the callForAllChanges(), only want to call saveCui at the end
bool bSaveCui = true;
int numPartialFiles;
YesNoIgnoreToggle yes = YesNoIgnoreToggle.yes;
YesNoIgnoreToggle no = YesNoIgnoreToggle.no;
// True when enterprise CUI file is loaded successfully
bool entCsLoaded;
// ed - access to the AutoCAD Command Line
// Allows us to write messages or Issue Commands in the interface
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
//Default Constructor
public CuiSamp()
{
// retrieve the location of, and open the ACAD Main CUI File
string mainCuiFile = (string)Application.GetSystemVariable("MENUNAME");
mainCuiFile += ".cuix";
cs = new CustomizationSection(mainCuiFile);
string entCuiFile = (string)Application.GetSystemVariable("ENTERPRISEMENU");
if (entCuiFile.Equals("."))
entCsLoaded = false;
else
{
entCs = new CustomizationSection(entCuiFile);
entCsLoaded = true;
}
// Code for loading all partial CUI's listed in the main CUI file
partials = new CustomizationSection[cs.PartialCuiFiles.Count];
int i = 0;
foreach (string fileName in cs.PartialCuiFiles)
{
if (File.Exists(fileName))
{
partials[i] = new CustomizationSection(fileName);
i++;
}
}
numPartialFiles = i;
}
// Command: savecui
// This Command saves all open CUI Files that have been modified
[CommandMethod("savecui")]
public void saveCui()
{
// Save all Changes made to the CUI file in this session.
// If changes were made to the Main CUI file - save it
// If changes were made to teh Partial CUI files need to save them too
if (cs.IsModified)
cs.Save();
for (int i = 0; i < numPartialFiles; i++)
{
if (partials[i].IsModified)
partials[i].Save();
}
if (entCsLoaded && entCs.IsModified)
entCs.Save();
// Here we unload and reload the main CUI file so the changes to the CUI file could take effect immediately.
Application.SetSystemVariable("FILEDIA", 0);
string cuiMenuGroup = cs.MenuGroup.Name;
Application.DocumentManager.MdiActiveDocument.SendStringToExecute("cuiunload " + cuiMenuGroup + " ", false, false, true);
string flName = cs.CUIFileName;
string flNameWithQuotes = "\"" + flName + "\"";
Application.DocumentManager.MdiActiveDocument.SendStringToExecute("cuiload " + flNameWithQuotes + "\n", false, false, true);
// Load all the partial CUIX files, They are not loaded when the main cuix file
// is loaded with command line version of CUILOAD
string fileNameWithQuotes;
partials = new CustomizationSection[cs.PartialCuiFiles.Count];
////int i = 0;
foreach (string fileName in cs.PartialCuiFiles)
{
if (File.Exists(fileName))
{
fileNameWithQuotes = "\"" + fileName + "\"";
Application.DocumentManager.MdiActiveDocument.SendStringToExecute("cuiload " + fileNameWithQuotes + "\n", false, false, true);
}
}
String currentWkspace = "Acme Workspace";
String cmdString = "WSCURRENT " + currentWkspace + "\n";
Application.DocumentManager.MdiActiveDocument.SendStringToExecute(cmdString, false, false, true);
cmdString = "RIBBON ";
Application.DocumentManager.MdiActiveDocument.SendStringToExecute(cmdString, false, false, true);
cmdString = "MENUBAR " + "1" + "\n"; ;
Application.DocumentManager.MdiActiveDocument.SendStringToExecute(cmdString, false, false, true);
Application.DocumentManager.MdiActiveDocument.SendStringToExecute("filedia 1 ", false, false, true);
}
// Lisp callable function: savecui
// Lisp wrapper for savecui command
[LispFunction("savecui")]
public ResultBuffer saveCui(ResultBuffer args)
{
saveCui();
return args;
}
// Command: addmenu
// This Command adds a new menu to all workspaces called Custom Menu, which contains 2 sub items
// The Menu is first added to the Main CUI File and then added to all it's workspaces.
[CommandMethod("addmenu")]
public void addMenu()
{
try
{
if (cs.MenuGroup.PopMenus.IsNameFree("Custom Menu"))
{
System.Collections.Specialized.StringCollection pmAliases = new System.Collections.Specialized.StringCollection();
//pmAliases.Add("POP12");
pmAliases.Add("POP18");
PopMenu pm = new PopMenu("Custom Menu", pmAliases, "Custom Menu", cs.MenuGroup);
addItemsToPM(pm);
addMenu2Workspaces(pm);
if (bSaveCui)
saveCui();
}
else
ed.WriteMessage("Custom Menu already Exists\n");
}
catch (System.Exception ex)
{
ed.WriteMessage(ex.ToString());
}
}
// Lisp callable function: addmenu
// Lisp wrapper for addmenu command
[LispFunction("addmenu")]
public ResultBuffer addMenu(ResultBuffer args)
{
addMenu();
return args;
}
// Add new Items to a PopMenu
private void addItemsToPM(PopMenu pm)
{
try
{
PopMenuItem pmi = new PopMenuItem(pm, -1);
pmi.MacroID = "ID_AUGI"; pmi.Name = "Autodesk User Group International";
pmi = new PopMenuItem(pm, -1);
pmi = new PopMenuItem(pm, -1);
pmi.MacroID = "ID_CustomSafe"; pmi.Name = "Online Developer Center";
}
catch (System.Exception ex)
{
ed.WriteMessage(ex.ToString());
}
}
// Add the menu to all the workspaces
private void addMenu2Workspaces(PopMenu pm)
{
try
{
foreach (Workspace wk in cs.Workspaces)
{
WorkspacePopMenu wkpm = new WorkspacePopMenu(wk, pm);
wkpm.Display = 1;
}
}
catch (System.Exception ex)
{
ed.WriteMessage(ex.ToString());
}
}
// Command: remmenu
// This Command deletes the menu added above from the Main CUI File and any
// workspaces that it was added to.
[CommandMethod("remmenu")]
public void remMenu()
{
// Find Index of the desired MenuItem
// Remove it from all Workspaces that it exists in
// Omitting this step leaves nasty left-overs in the Workspace files
// Remove it from the Cui files' Menu List
try
{
PopMenu pm = cs.MenuGroup.PopMenus.FindPopWithAlias("POP18");
if (pm != null)
{
foreach (Workspace wk in cs.Workspaces)
{
WorkspacePopMenu wkPm = wk.WorkspacePopMenus.FindWorkspacePopMenu(pm.ElementID, pm.Parent.Name);
if (wkPm != null)
wk.WorkspacePopMenus.Remove(wkPm);
}
cs.MenuGroup.PopMenus.Remove(pm); // Deletes the Menu from ACAD Menu Group
if (bSaveCui)
saveCui();
}
}
catch (System.Exception ex)
{
ed.WriteMessage(ex.ToString());
}
}
// Lisp callable function: remmenu
// Lisp wrapper for remmenu command
[LispFunction("remmenu")]
public ResultBuffer remMenu(ResultBuffer args)
{
remMenu();
return args;
}
// Command: addws
// This command adds a new workspace. The name of the workspace to create is
// obtained from the command line.
[CommandMethod("addws")]
public void addws()
{
String wsName;
PromptResult prs = ed.GetString("Enter name of workspace to create: ");
try
{
if (PromptStatus.OK == prs.Status)
{
wsName = prs.StringResult;
if (-1 == cs.Workspaces.IndexOfWorkspaceName(wsName)) // If the workspace doesnot exist
{
Workspace nwWs = new Workspace(cs, wsName); // Create the workspace
if (bSaveCui)
saveCui(); // Save and reload the CUI file
}
else
{
ed.WriteMessage("A workspace with this name already exists");
}
}
}
catch (System.Exception ex)
{
ed.WriteMessage("Exception: {0}", ex.Message);
}
}
// Lisp callable function: addws
// Lisp wrapper for addws command
[LispFunction("addws")]
public ResultBuffer addws(ResultBuffer args)
{
addws();
return args;
}
// Command: remws
// This command removes a workspace. The name of the workspace to remove is
// obtained from the command line.
[CommandMethod("remws")]
public void remws()
{
try
{
String wsName;
PromptResult prs = ed.GetString("Enter name of workspace to remove: ");
if (PromptStatus.OK == prs.Status)
{
wsName = prs.StringResult;
if (-1 != cs.Workspaces.IndexOfWorkspaceName(wsName)) // If the workspace exists
{
cs.deleteWorkspace(wsName); // Remove the workspace
if (bSaveCui)
saveCui(); // Save and reload the CUI file
}
else
{
ed.WriteMessage("No workspace exists with this name");
}
}
}
catch (System.Exception ex)
{
ed.WriteMessage("Exception: {0}", ex.Message);
}
}
// Lisp callable function: remws
// Lisp wrapper for remws command
[LispFunction("remws")]
public ResultBuffer remws(ResultBuffer args)
{
remws();
return args;
}
// Command: cuishortcut
// This adds a Shortcut key to the CUI command.
// Ctrl+B is used for Toggling SNAP. It gets reassigned
[CommandMethod("cuishortcut")]
public void shortCut()
{
try
{
// In here we will make a shortcut Key combination to the Customize.. command
MacroGroup mg = cs.MenuGroup.MacroGroups[0]; // Search the ACAD Macros
foreach (MenuMacro mcr in mg.MenuMacros)
{
if (mcr.ElementID.Equals("MM_1635"))
{
MenuAccelerator ma = new MenuAccelerator(mcr, cs.MenuGroup);
ma.AcceleratorShortcutKey = "CTRL+B";
if (bSaveCui)
saveCui();
}
}
}
catch (System.Exception ex)
{
ed.WriteMessage("Exception: {0}", ex.Message);
}
}
// Lisp callable function: cuishortcut
// Lisp wrapper for cuishortcut command
[LispFunction("cuishortcut")]
public ResultBuffer shortCut(ResultBuffer args)
{
shortCut();
return args;
}
// Command: dockf
// Set Properties palette to float
[CommandMethod("dockf")]
public void dockInfoPalF()
{
dockInfoPalette(DockableWindowOrient.floating);
}
// Lisp callable function: dockf
// Lisp wrapper for dockf command
[LispFunction("dockf")]
public ResultBuffer dockInfoPalF(ResultBuffer args)
{
dockInfoPalF();
return args;
}
// Method to implement the positiioning/docking of the "Properties" window
private void dockInfoPalette(DockableWindowOrient orientation)
{
int wkB = cs.Workspaces.IndexOfWorkspaceName("Acme Workspace");
// check to see if it exists
if (wkB == -1)
{
// if not, then see if it is called simply AutoCAD
wkB = cs.Workspaces.IndexOfWorkspaceName("AutoCAD");
if (wkB == -1)
{
// if not, then ok - it's something else
Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Workspace not found.");
return;
}
}
Workspace wk = cs.Workspaces[wkB];
foreach (WorkspaceDockableWindow dockableWindow in wk.DockableWindows)
{
//if(dockableWindow.Name.Equals("Info Palette"))
if (dockableWindow.Name.Equals("Properties"))
{
if (orientation.Equals(DockableWindowOrient.floating))
dockableWindow.DockFloat = DockedFloatingIgnoreToggle.floating;
else
dockableWindow.DockFloat = DockedFloatingIgnoreToggle.docked;
dockableWindow.Display = yes;
dockableWindow.Orientation = orientation;
dockableWindow.AutoHide = OnOffIgnoreToggle.off;
dockableWindow.UseTransparency = no;
if (bSaveCui)
saveCui();
break;
}
}
}
// Command: addtoolbar
// Creates a new toolbar called "New Toolbar", and adds it to all workspaces.
// This toolbar contains a Toolbar control for named view, button for drawing
// a pline, and a flyout that uses the "Draw" tool bar.
[CommandMethod("addtoolbar")]
public void addToolbar()
{
try
{
Toolbar newTb = new Toolbar("New Toolbar", cs.MenuGroup);
newTb.ToolbarOrient = ToolbarOrient.floating;
newTb.ToolbarVisible = ToolbarVisible.show;
ToolbarControl tbCtrl = new ToolbarControl(ControlType.NamedViewControl, newTb, -1);
ToolbarButton tbBtn = new ToolbarButton(newTb, -1);
tbBtn.Name = "PolyLine";
tbBtn.MacroID = "ID_Pline";
ToolbarFlyout tbFlyout = new ToolbarFlyout(newTb, -1);
tbFlyout.ToolbarReference = "DRAW";
foreach (Workspace wk in cs.Workspaces)
{
WorkspaceToolbar wkTb = new WorkspaceToolbar(wk, newTb);
wk.WorkspaceToolbars.Add(wkTb);
wkTb.Display = 1;
}
if (bSaveCui)
saveCui();
}
catch (System.Exception ex)
{
ed.WriteMessage(ex.ToString());
}
}
// Lisp callable function: addtoolbar
// Lisp wrapper for addtoolbar command
[LispFunction("addtoolbar")]
public ResultBuffer addToolbar(ResultBuffer args)
{
addToolbar();
return args;
}
// Command: remtoolbar
// This Command removes the toolbar added above from the Main CUI File and any
// workspaces that it was added to.
[CommandMethod("remtoolbar")]
public void remToolbar()
{
try
{
Toolbar tbr = cs.MenuGroup.Toolbars.FindToolbarWithName("New Toolbar");
if (tbr != null)
{
foreach (Workspace wk in cs.Workspaces)
{
WorkspaceToolbar wkTb = wk.WorkspaceToolbars.FindWorkspaceToolbar(tbr.ElementID, tbr.Parent.Name);
if (wkTb != null)
wk.WorkspaceToolbars.Remove(wkTb);
}
cs.MenuGroup.Toolbars.Remove(tbr); // Deletes the toolbar from ACAD Menu Group
if (bSaveCui)
saveCui();
}
}
catch (System.Exception ex)
{
ed.WriteMessage(ex.ToString());
}
}
// Lisp callable function: remtoolbar
// Lisp wrapper for remtoolbar command
[LispFunction("remtoolbar")]
public ResultBuffer remToolbar(ResultBuffer args)
{
remToolbar();
return args;
}
// Command: tempkey
// This command will install a temporary override key. Temporary override keys are keys that temporarily
// turn on or turn off one of the drawing aids that are set in the Drafting Settings dialog box
// (for example, Ortho mode, object snaps, or Polar mode).
[CommandMethod("tempkey")]
public void tempOverride()
{
try
{
TemporaryOverride newTempOverride = new TemporaryOverride(cs.MenuGroup);
newTempOverride.OverrideShortcutKey = "SHIFT+Y"; // Scan code for Y
newTempOverride.Name = "Customization Override";
newTempOverride.Description = "Customization Override";
newTempOverride.ElementID = "EID_CUITEMPOVERRIDE";
// Creating a override for Shift+Y (Key down) that will behave as temporary override for OSnap to endpoint (MM_1629)
OverrideItem newOverrideItem = new OverrideItem("MM_1629", OverrideKeyState.Down, newTempOverride);
newTempOverride.DownOverride = newOverrideItem;
if (bSaveCui)
saveCui();
}
catch (System.Exception ex)
{
ed.WriteMessage(ex.ToString());
}
}
// Lisp callable function: tempkey
// Lisp wrapper for tempkey command
[LispFunction("tempkey")]
public ResultBuffer tempOverride(ResultBuffer args)
{
tempOverride();
return args;
}
// Command: dblclick
// This command adds a double click action for polylines (Non-LWpolylines like 2D polylines).
// After running this command, When we double click a polyline (i.e., a non-light weight polyline),
// the "Properties" window is launched. This replaces the original behaviour where "pedit" was launched.
[CommandMethod("dblclick")]
public void doubleClick()
{
DoubleClickAction dblClickAction = new DoubleClickAction(cs.MenuGroup, "My Double click", -1);
dblClickAction.Description = "Double Click Customization";
dblClickAction.ElementID = "EID_mydblclick";
dblClickAction.DxfName = "Polyline";
DoubleClickCmd dblClickCmd = new DoubleClickCmd(dblClickAction);
dblClickCmd.MacroID = "ID_Ai_propch";
dblClickAction.DoubleClickCmd = dblClickCmd;
if (bSaveCui)
saveCui();
}
// Lisp callable function: dblclick
// Lisp wrapper for dblclick command
[LispFunction("dblclick")]
public ResultBuffer doubleClick(ResultBuffer args)
{
doubleClick();
return args;
}
// Command: cuiall
// Issuing this command will run the methods to make all changes to the UI
// This will add the custom menu, toolbar, and RibbonElement, as well as
// dock the Properties palette on the right side.
[CommandMethod("cuiall")]
public void callForAllChanges()
{
bSaveCui = false;
addws();
addMenu();
addToolbar();
dockInfoPalF();
addRibbonElements();
saveCui();
}
// Lisp callable function: cuiall
// Lisp wrapper for cuiall command
[LispFunction("cuiall")]
public ResultBuffer callForAllChanges(ResultBuffer args)
{
callForAllChanges();
return args;
}
[CommandMethod("addRibbonElements")]
public void addRibbonElements()
{
RibbonRoot ribbonRoot = cs.MenuGroup.RibbonRoot;
RibbonPanelSourceCollection panels = ribbonRoot.RibbonPanelSources;
RibbonPanelSource ribPanelSource = new RibbonPanelSource(ribbonRoot);
ribPanelSource.Text = "MyPanel";
// Add a RibbonRow
RibbonRow ribRow = new RibbonRow();
//Add the RibbonRow to the RibbonPanel
ribPanelSource.Items.Add((RibbonItem)ribRow);
//Create a Ribbon Command Button
RibbonCommandButton ribCommandButton = createRibbonCmdButton(ribRow, "MyButton", "ID_CircleRad", false);
//Add the ribbon command button to the ribbon row
ribRow.Items.Add((RibbonItem)ribCommandButton);
// Create a Ribbon Command Button to add to the RibbonSplitButton
// created next. Create a new command
RibbonCommandButton ribCommandButton2 = createRibbonCmdButton(ribRow, "MyButton", "ID_CircleRad", true);
String strSplitButtonID = "mySplitButton_ID";
string splitButtonName = "mySplitButton";
RibbonSplitButton ribSplitButton;
ribSplitButton = createRibbonSplitButton(ribRow, ribCommandButton2, splitButtonName, strSplitButtonID);
//Add the ribbon split button to the ribbon row
ribRow.Items.Add((RibbonItem)ribSplitButton);
// Add the Ribbon Panel Source to the Ribbon Panels
panels.Add(ribPanelSource);
// Create a new Ribbon Tab Source
RibbonTabSource tabsrc=null;
tabsrc=new RibbonTabSource(ribbonRoot);
tabSrc.Name = "MyTab";
tabSrc.Text = "MyTab";
//Add the Ribbon Tab Source to the collection
RibbonTabSourceCollection tabs = null;
tabs = ribbonRoot.RibbonTabSources;
tabs.Add(tabSrc);
//Add the Panel to the Tab
RibbonPanelSourceReference ribPanelSourceRef = null;
ribPanelSourceRef = new RibbonPanelSourceReference(tabSrc);
ribPanelSourceRef.PanelId = ribPanelSource.ElementID;
ribPanelSourceRef.ElementID = "MyElementId";
tabSrc.Items.Add(ribPanelSourceRef);
// Add the tab to the work space
AddTabToWorkspace("Acme Workspace", tabSrc.ElementID);
if(bSaveCui)
saveCui();
}
RibbonCommandButton createRibbonCmdButton(RibbonRow ribRow, String buttonName, String strMacroID, bool bCreateNewCmd)
{
//Create a Ribbon Command Button
RibbonCommandButton ribCommandButton = new RibbonCommandButton(ribRow);
ribCommandButton.Text = buttonName;
if (bCreateNewCmd)
{
MacroGroup macGroup;
macGroup = cs.MenuGroup.MacroGroups[0];
//This will add a new Command,
MenuMacro menuMac;
//Just using an existing identifer for the icons
menuMac = macGroup.CreateMenuMacro("testCommandWB", "^C^CLine ", "ID_MyLineCmdWB", "My line help",
MacroType.Any, "RCDATA_16_3DALIGN", "RCDATA_32_3DALIGN", "Test command label");
ribCommandButton.MacroID = menuMac.ElementID;
}
else
{
ribCommandButton.MacroID = strMacroID;
}
return ribCommandButton;
}
RibbonSplitButton createRibbonSplitButton(RibbonRow ribRow, RibbonCommandButton ribCmdButton, String splitButtonName, String strSplitButtonID)
{
//Create a Ribbon Command Button
RibbonSplitButton ribSplitButton = new RibbonSplitButton(ribRow);
ribSplitButton.Text = splitButtonName;
ribSplitButton.ButtonStyle = RibbonButtonStyle.SmallWithoutText;
ribSplitButton.ListStyle = RibbonSplitButtonListStyle.IconText;
String SplitbuttonElementID = strSplitButtonID; // "mySplitButton_ID";
ribSplitButton.ElementID = SplitbuttonElementID;
RibbonSplitButtonBehavior rsbehavior = RibbonSplitButtonBehavior.DropDownFollow;
ribSplitButton.Behavior = rsbehavior;
RibbonSplitButtonListStyle rsStyle = RibbonSplitButtonListStyle.IconText;
ribSplitButton.ListStyle = rsStyle;
ribSplitButton.LargeImage = "";
RibbonButtonStyle rsButtonStyle = RibbonButtonStyle.LargeWithHorizontalText;
ribSplitButton.ButtonStyle = rsButtonStyle;
string sKeyTip = "my Key Tip";
ribSplitButton.KeyTip = sKeyTip;
ribSplitButton.Items.Add(ribCmdButton);
return ribSplitButton;
}
public void AddTabToWorkspace(String strWrkSpaceName, String strTabName)
{
// This command adds the tab to the Acme Workspace
WSRibbonRoot wrkSpaceRibbonRoot = null;
WorkspaceRibbonTabCollection wsRibbonTabCollection = null;
WSRibbonTabSourceReference wsRibTabSrcRef = null;
try
{
WorkspaceCollection WsCollect = cs.Workspaces;
if ((WsCollect.Count <= 0))
{
ed.WriteMessage("Failed to Get the WorkspaceCollection\n");
return;
}
for (int i = 0; i < WsCollect.Count; i++)
{
//If the name of the Workspace is "Acme Workspace" then get the WSRibbonRoot
if (WsCollect[i].Name == strWrkSpaceName)
{
wrkSpaceRibbonRoot = WsCollect[i].WorkspaceRibbonRoot;
i = WsCollect.Count; //Exit for loop
}
}
if (wrkSpaceRibbonRoot == null)
{
ed.WriteMessage("Acme Workspace WSRibbonRoot Not found\n");
return;
}
//Create the WSRibbonTabSourceReference from RibbonTabSource (insert tab - ID_TabInsert)
wsRibTabSrcRef = createWSRibbonTabSrcReference(strTabName, cs);
if (wsRibTabSrcRef == null)
{
ed.WriteMessage("Failed to create WSRibbonTabSourceReference\n");
return;
}
//Get the Tabcollection in the Acme Workspace
wsRibbonTabCollection = wrkSpaceRibbonRoot.WorkspaceTabs;
if (wsRibbonTabCollection.Count <= 0)
{
ed.WriteMessage("Acme Workspace does not currently contain any Tabs\n");
}
//Get a count of the Ribbons in the ribbon collection in Acme Workspace
int intialTabCount = wsRibbonTabCollection.Count;
// Make the parent of the WSRibbonTabSourceReference the Acme Workspace RibbonRoot
wsRibTabSrcRef.SetParent(wrkSpaceRibbonRoot);
//Add the WSRibbonTabSourceReference to the Acme Workspace Ribbon Tab collection
wsRibbonTabCollection.Add(wsRibTabSrcRef);
//Check the count of the Ribbon Tab collection verifies the new Tab was added
if (wsRibbonTabCollection.Count != intialTabCount + 1)
{
ed.WriteMessage("Failed To add WSRibbonTabSourceReference to Acme Workspace");
return;
}
}
catch (System.Exception es)
{
ed.WriteMessage(es.Message);
}
finally
{
if (wrkSpaceRibbonRoot != null)
wrkSpaceRibbonRoot = null;
if (wsRibTabSrcRef != null)
wsRibTabSrcRef = null;
if (wsRibbonTabCollection != null)
wsRibbonTabCollection = null;
}
}
WSRibbonTabSourceReference createWSRibbonTabSrcReference(String sTabId, CustomizationSection custSection)
{
RibbonTabSource ribTabsrc=null;
RibbonRoot ribbonRoot = null;
WSRibbonTabSourceReference wsRibTabSrcRef = null;
ribbonRoot = cs.MenuGroup.RibbonRoot;
if (ribbonRoot == null)
{
ed.WriteMessage("RibbonRoot Not found\n");
return null;
}
//Find the the Tab
ribTabsrc=ribbonRoot.FindTab(sTabId);
// Make sure the Ribbon Tab is found
if (ribTabsrc== null)
{
ed.WriteMessage("Ribbon Tab Not found\n");
return null;
}
//Create the WSRibbonTabSourceReference using the RibbonTabSource
wsRibTabSrcRef = WSRibbonTabSourceReference.Create(ribTabSrc);
//Return the WSRibbonTabSourceReference
return wsRibTabSrcRef;
}
[LispFunction("addRibbonElements")]
public ResultBuffer addRibbonElements(ResultBuffer args)
{
addRibbonElements();
return args;
}
}
public class CUIStartup : IExtensionApplication
{
// Used to support the saving and updating of CUI settings.
[DllImport("acad.exe", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl, EntryPoint = "acedCmd")]
private static extern int acedCmd(System.IntPtr vlist);
//Constants used frequently below
const String WORKSPACENAME = "Acme Workspace";
const String ACADDEFAULT = "AutoCAD Default";
const String ACADCLASSIC = "AutoCAD Classic";
// All Cui files (main/partial/enterprise) have to be loaded into an object of class
// CustomizationSection
// cs - main AutoCAD CUI file
CustomizationSection cs;
// ed - access to the AutoCAD Command Line
// Allows us to write messages or Issue Commands in the interface
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
[DllImport("acad.exe", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ads_queueexpr")]
extern static int ads_queueexpr(byte[] command);
public void Initialize()
{
try
{
// Create and fill the new Workspace, if it is not already filled.
bool bCreated = false;
Workspace newWs = CreateOrGetWorkspace(ref bCreated); // ...and recreate it anew.
if (bCreated == true)
{
// If we happened to create the workspace, then send the following commands to make sure the UI is updated immediately.
// UPDATECUI simply calls the SaveCUI method below.
// WSCURRENT sets the Workspace to our newly created workspace.
// The reason these must be issued via ads_queueexpr() is that AutoCAD is not yet ready to receive UI directives
// that update the editor - sending these through ads_queueexpr() will ensure that the request is sufficiently delayed.
UnicodeEncoding uEncode = new UnicodeEncoding();
ads_queueexpr(uEncode.GetBytes("(Command \"_UPDATECUI\")"));
ads_queueexpr(uEncode.GetBytes("(Command \"WSCURRENT\" \"" + WORKSPACENAME + "\")"));
}//if
}
catch (System.Exception ex)
{
ed.WriteMessage("Error: " + ex.Message);
}
}
public void Terminate() { }
//Default Constructor
public CUIStartup()
{
// retrieve the location of, and open the ACAD Main CUI File
string mainCuiFile = (string)Application.GetSystemVariable("MENUNAME");
mainCuiFile += ".cuix";
cs = new CustomizationSection(mainCuiFile);
}
// This command will add the workspace if it does not exist and the UI elements.
// If the workspace settings have been modified, they will be reset to what was
// done by this example.
[CommandMethod("ADDACMEWS")]
public void addAcmeWorkspace()
{
try
{
RemoveAllComponents(); // Remove the workspace, if it exists...
bool bCreated = false;
Workspace newWs = CreateOrGetWorkspace(ref bCreated); // ...and recreate it anew.
if (bCreated == true)
{
// In this case, we have the luxury of having the UI ready for CUI directives.
// We can simply call SaveCui and
// directly set the WSCURRENT variable without the need to send to the commandline.
saveCui(); // Save and reload the CUI file
// Set the workspace to the new/updated workspace.
Application.SetSystemVariable("WSCURRENT", WORKSPACENAME);
}
}
catch (System.Exception ex)
{
ed.WriteMessage("Error: " + ex.Message);
}
}
// This method will return the custom workspace, creating it if necessary.
public Workspace CreateOrGetWorkspace(ref bool bCreated)
{
Workspace newWs;
// If the workspace does not exist
if (-1 == cs.Workspaces.IndexOfWorkspaceName(WORKSPACENAME))
{
newWs = new Workspace(cs, WORKSPACENAME); // Create the workspace
// Call each of these helper methods in-turn to create the CUI content.
addMyMenu(newWs);// Fill it with our menu's - custom and standard.
addMyToolbar(newWs); // new custom and standard Toolbar
// Save the changes...
if (cs.IsModified)
cs.Save();
bCreated = true;
}
else // Otherwise, just return the existing workspace.
{
bCreated = false;
newWs = cs.getWorkspace(WORKSPACENAME);
}
return newWs;
}
// **************** Add a Custom Menu to the Workspace********************
void addMyMenu(Workspace newWs)
{
// Create a custom Menu. This will have the BOX and PYRAMID commands as well as the User Group and Online Developer Center
// Command entries.
// Give the toolbar an alias name.
System.Collections.Specialized.StringCollection pmAliases = new System.Collections.Specialized.StringCollection();
pmAliases.Add("MyCustomMenu");
PopMenu pm = new PopMenu("Custom Menu", pmAliases, "Custom Menu", cs.MenuGroup);
addItemsToPM(pm); // Populate it with the menu entries...
WorkspacePopMenu wkpm = new WorkspacePopMenu(newWs, pm);
wkpm.Display = 1;
// Now, add some Standard Toolbars from the *AutoCAD Default* or *AutoCAD Classic* Workspace
// First, get the AutoCAD Default workspace...
Workspace defaultWS = cs.getWorkspace(ACADDEFAULT);
if (defaultWS == null)
{
// If it is not found, get the AutoCAD Classic workspace...
defaultWS = cs.getWorkspace(ACADCLASSIC);
if (defaultWS == null)
throw new ApplicationException("Default AutoCAD Workspaces not found!");
}
// Add the standard "Help" Menu
WorkspacePopMenu stMenu = defaultWS.WorkspacePopMenus.FindWorkspacePopMenu("ID_MnHelp", cs.MenuGroup.Name);
if (stMenu != null)
{
WorkspacePopMenu stNewMenu = new WorkspacePopMenu(newWs, stMenu);
//newWs.WorkspacePopMenus.Insert(0, stNewMenu);
stNewMenu.Display = 1;
}
// Add the standard "Window" Menu
stMenu = defaultWS.WorkspacePopMenus.FindWorkspacePopMenu("ID_MnWindow", cs.MenuGroup.Name);
if (stMenu != null)
{
WorkspacePopMenu stNewMenu = new WorkspacePopMenu(newWs, stMenu);
//newWs.WorkspacePopMenus.Insert(0, stNewMenu);
stNewMenu.Display = 1;
}
// Add the standard "File" Menu
stMenu = defaultWS.WorkspacePopMenus.FindWorkspacePopMenu("ID_MnFile", cs.MenuGroup.Name);
if (stMenu != null)
{
WorkspacePopMenu stNewMenu = new WorkspacePopMenu(newWs, stMenu);
//newWs.WorkspacePopMenus.Insert(0, stNewMenu);
stNewMenu.Display = 1;
}
}
// **************** Add a Custom Toolbar to the workspace*******************
void addMyToolbar(Workspace newWs)
{
// Create a custom toolbar with the Polyline command and the Draw Flyout - along with the Layer dropdown control.
// Create the toolbar
Toolbar newTb = new Toolbar("my New Toolbar", cs.MenuGroup);
newTb.ToolbarOrient = ToolbarOrient.floating;
newTb.ToolbarVisible = ToolbarVisible.show;
// Add the Polyline command
ToolbarButton tbBtn = new ToolbarButton(newTb, -1);
tbBtn.Name = "PolyLine";
tbBtn.MacroID = "ID_Pline";
// Add the 'Draw' Flyout.
ToolbarFlyout tbFlyout = new ToolbarFlyout(newTb, -1);
tbFlyout.ToolbarReference = "DRAW";
// Now add the Layer control.
ToolbarControl tbCtrl = new ToolbarControl(ControlType.LayerControl, newTb, -1);
// Add the toolbar to the workspace
WorkspaceToolbar wkTb = new WorkspaceToolbar(newWs, newTb);
newWs.WorkspaceToolbars.Add(wkTb);
wkTb.Display = 1;
// Now, add some *Standard Toolbars* from the AutoCAD Default Workspace
// First, get the AutoCAD Default workspace...
Workspace defaultWS = cs.getWorkspace(ACADDEFAULT);
if (defaultWS == null)
{
// If it is not found, get the AutoCAD Classic workspace...
defaultWS = cs.getWorkspace(ACADCLASSIC);
if (defaultWS == null)
throw new ApplicationException("Default AutoCAD Workspaces not found!");
}
// Get the Standard toolbar and add it here - so we have some stock commands available.
WorkspaceToolbar stWtb = defaultWS.WorkspaceToolbars.FindWorkspaceToolbar("ID_TbStandar", cs.MenuGroup.Name);
if (stWtb != null)
{
WorkspaceToolbar stNewWtb = new WorkspaceToolbar(newWs, stWtb);
//newWs.WorkspaceToolbars.Insert(0, stWtb);
stNewWtb.Display = 1;
}
// Add the Workspaces toolbar, so we can switch back quickly...
stWtb = defaultWS.WorkspaceToolbars.FindWorkspaceToolbar("ID_TbWorkspaces", cs.MenuGroup.Name);
if (stWtb != null)
{
WorkspaceToolbar stNewWtb = new WorkspaceToolbar(newWs, stWtb);
//newWs.WorkspaceToolbars.Insert(0, stWtb);
stNewWtb.Display = 1;
}
}
// Add new Items to a PopMenu
private void addItemsToPM(PopMenu pm)
{
PopMenuItem pmi = new PopMenuItem(pm, -1);
pmi.MacroID = "ID_AUGI"; pmi.Name = "Autodesk User Group International";
pmi = new PopMenuItem(pm, -1);
pmi.MacroID = "ID_CustomSafe"; pmi.Name = "Online Developer Center";
pmi = new PopMenuItem(pm, -1); // Separator
pmi = new PopMenuItem(pm, -1);
pmi.MacroID = "ID_Box";
pmi.Name = "Box";
pmi = new PopMenuItem(pm, -1);
pmi.MacroID = "ID_Pyramid";
pmi.Name = "Pyramid";
}
// Here is an example of how we can remove all of our UI elements. This code can be run from out-of-process during uninstallation
// of the product, though is not demonstrated here. We still recommend that you load the CUI elements from first-run AutoCAD.
[CommandMethod("REMOVEALL")]
public void RemoveAllComponents()
{
Workspace newWs;
if (-1 == cs.Workspaces.IndexOfWorkspaceName(WORKSPACENAME)) // If the workspace doesnot exist
return;
else
newWs = cs.getWorkspace(WORKSPACENAME);
// Remove the Menus collection...
while (newWs.WorkspacePopMenus.Count > 0)
newWs.WorkspacePopMenus.RemoveAt(0);
// Clear out the Custom Menu group...
if (cs.MenuGroup.PopMenus.IsNameFree("Custom Menu") == false)
{
PopMenu pop = cs.MenuGroup.PopMenus.FindPopWithName("Custom Menu");
cs.MenuGroup.PopMenus.Remove(pop);
}
// Next, make sure the workspace toolbars collection is empty
while (newWs.WorkspaceToolbars.Count > 0)
newWs.WorkspaceToolbars.RemoveAt(0);
// Clear out the Custom Menu group...
if (cs.MenuGroup.Toolbars.IsNameFree("New Toolbar") == false)
{
Toolbar tb = cs.MenuGroup.Toolbars.FindToolbarWithName("New Toolbar");
cs.MenuGroup.Toolbars.Remove(tb);
}
// Remove the workspace
if (cs.Workspaces.IndexOfWorkspaceName(WORKSPACENAME) > 0) // If the workspace does not exist
cs.Workspaces.Remove(cs.Workspaces.IndexOfWorkspaceName(WORKSPACENAME));
saveCui(); // Save and reload the CUI file
Application.SetSystemVariable("WSCURRENT", ACADCLASSIC);
}
[CommandMethod("UPDATECUI")]
public void saveCui()
{
// Save all Changes made to the CUI file in this session.
// If changes were made to the Main CUI file - save it
// If changes were made to teh Partial CUI files need to save them too
if (cs.IsModified)
cs.Save();
// Here we unload and reload the main CUI file so the changes to the CUI file could take effect immediately.
// To do this we P/Invoke into acedCmd() in order to synchronously call the CUIUNLOAD / CUILOAD command, disarming and
// rearming the file dialog during the process.
ResultBuffer rb = new ResultBuffer();
// RTSTR = 5005
rb.Add(new TypedValue(5005, "FILEDIA"));
rb.Add(new TypedValue(5005, "0"));
// start the insert command
acedCmd(rb.UnmanagedObject);
//CUIUNLOAD
string cuiMenuGroup = cs.MenuGroup.Name;
rb = new ResultBuffer();
rb.Add(new TypedValue(5005, "_CUIUNLOAD"));
rb.Add(new TypedValue(5005, cuiMenuGroup));
acedCmd(rb.UnmanagedObject);
//CUILOAD
string cuiFileName = cs.CUIFileName;
rb = new ResultBuffer();
rb.Add(new TypedValue(5005, "_CUILOAD"));
rb.Add(new TypedValue(5005, cuiFileName));
acedCmd(rb.UnmanagedObject);
// Load all the partial CUIX files, They are not loaded when the main cuix file
// is loaded with command line version of CUILOAD
CustomizationSection[] partials;
//int numPartialFiles;
string fileNameWithQuotes;
partials = new CustomizationSection[cs.PartialCuiFiles.Count];
////int i = 0;
foreach (string fileName in cs.PartialCuiFiles)
{
if (File.Exists(fileName))
{
fileNameWithQuotes = "\"" + fileName + "\"";
//Application.DocumentManager.MdiActiveDocument.SendStringToExecute("cuiload " + fileNameWithQuotes + "\n", false, false, true);
rb = new ResultBuffer();
rb.Add(new TypedValue(5005, "_CUILOAD"));
rb.Add(new TypedValue(5005, fileNameWithQuotes));
acedCmd(rb.UnmanagedObject);
}
}
//FILEDIA back on
rb = new ResultBuffer();
rb.Add(new TypedValue(5005, "FILEDIA"));
rb.Add(new TypedValue(5005, "1"));
acedCmd(rb.UnmanagedObject);
}
}
}