乐筑天下

搜索
欢迎各位开发者和用户入驻本平台 尊重版权,从我做起,拒绝盗版,拒绝倒卖 签到、发布资源、邀请好友注册,可以获得银币 请注意保管好自己的密码,避免账户资金被盗
查看: 29|回复: 1

Kean专题(17)—Plugin of the Month

[复制链接]

72

主题

2726

帖子

9

银币

社区元老

Rank: 75Rank: 75Rank: 75

铜币
3014
发表于 2010-2-3 21:42:00 | 显示全部楼层 |阅读模式
一、剪贴板管理器
Clipboard Manager: October’s ADN Plugin of the Month, now live on Autodesk Labs
As Scott is leaving on a well-deserved sabbatical, he has gone ahead and posted our next Plugin of the Month a few days ahead of schedule. Here’s a link to Scott’s post announcing the tool.
This is a very cool little application developed by Mark Dubbelaar from Australia. Mark has been drafting/designing with  for the last 10+ years and, during this time, has used a variety of programming languages to customize AutoCAD: LISP, VBA and now VB.NET. Mark was inspired by the “clipboard ring” functionality that used to be in Microsoft Office (at least I say “used to be” because I haven’t found it in Office 2007), and decided to implement similar functionality in AutoCAD.
The implementation of the tool is quite straightforward but the functionality is really very compelling: after having NETLOADed the tool and run the CLIPBOARD command, as you use Ctrl-C to copy drawing objects from inside AutoCAD to the clipboard a custom palette gets populated with entries containing these sets of objects. Each entry contains a time-stamp and an automatically-generated name which you can then change to something more meaningful.
When you want to use these clipboard entries, you simply right-click on one and choose the appropriate paste option (which ultimately just calls through to the standard AutoCAD paste commands, PASTECLIP, PASTEBLOCK and PASTEORIG, reducing the complexity of the tool).

ns55gn12hjb.png

ns55gn12hjb.png


That’s really all there is to it: a simple yet really useful application. Thanks for providing such a great little tool, Mark! :-)
Under the hood, the code is quite straightforward. The main file, Clipboard.vb, sets up the application to create demand-loading entries when first loaded into AutoCAD and defines a couple of commands – CLIPBOARD and REMOVECB, which removes the demand-loading entries to “uninstall” the application. It also contains the PaletteSet that contains our CbPalette and gets displayed by the CLIPBOARD command.
  1. Imports Autodesk.AutoCAD.Runtime
  2. Imports Autodesk.AutoCAD.Windows
  3. Imports Autodesk.AutoCAD.EditorInputPublic Class ClipBoard
  4.   Implements IExtensionApplication   _
  5.   Private _cp As CbPalette = Nothing  Public ReadOnly Property ClipboardPalette() As CbPalette
  6.     Get
  7.       If _cp Is Nothing Then
  8.         _cp = New CbPalette
  9.       End If
  10.       Return _cp
  11.     End Get
  12.   End Property  Private _ps As PaletteSet = Nothing  Public ReadOnly Property PaletteSet() As PaletteSet
  13.     Get
  14.       If _ps Is Nothing Then
  15.         _ps = New PaletteSet("Clipboard", _
  16.           New System.Guid("ED8CDB2B-3281-4177-99BE-E1A46C3841AD"))
  17.         _ps.Text = "Clipboard"
  18.         _ps.DockEnabled = DockSides.Left + _
  19.           DockSides.Right + DockSides.None
  20.         _ps.MinimumSize = New System.Drawing.Size(200, 300)
  21.         _ps.Size = New System.Drawing.Size(300, 500)
  22.         _ps.Add("Clipboard", ClipboardPalette)
  23.       End If
  24.       Return _ps
  25.     End Get
  26.   End Property  Private Sub Initialize() _
  27.     Implements IExtensionApplication.Initialize    DemandLoading.RegistryUpdate.RegisterForDemandLoading()
  28.   End Sub  Private Sub Terminate() _
  29.     Implements IExtensionApplication.Terminate  End Sub   _
  30.   Public Sub ShowClipboard()    PaletteSet.Visible = True  End Sub   _
  31.   Public Sub RemoveClipboard()    DemandLoading.RegistryUpdate.UnregisterForDemandLoading()
  32.     Dim ed As Editor = _
  33.       Autodesk.AutoCAD.ApplicationServices.Application _
  34.       .DocumentManager.MdiActiveDocument.Editor()
  35.     ed.WriteMessage(vbCr + _
  36.       "The Clipboard Manager will not be loaded" _
  37.       + " automatically in future editing sessions.")  End Sub
  38. End Class
It’s the Clipboard_Palette.vb file that contains the more interesting code, implementing the behaviour of the CbPalette object. The real “magic” is how it hooks into AutoCAD’s COPYCLIP by attaching itself as the default “clipboard viewer”.
  1. Imports AcApp = Autodesk.AutoCAD.ApplicationServices.Application
  2. Imports System.Windows.FormsPublic Class CbPalette  ' Constants for Windows API calls  Private Const WM_DRAWCLIPBOARD As Integer = &H308
  3.   Private Const WM_CHANGECBCHAIN As Integer = &H30D  ' Handle for next clipboard viewer  Private _nxtCbVwrHWnd As IntPtr  ' Boolean to control access to clipboard data  Private _internalHold As Boolean = False  ' Counter for our visible clipboard name  Private _clipboardCounter As Integer = 0  ' Windows API declarations  Declare Auto Function SetClipboardViewer Lib "user32" _
  4.     (ByVal HWnd As IntPtr) As IntPtr
  5.   Declare Auto Function SendMessage Lib "User32" _
  6.     (ByVal HWnd As IntPtr, ByVal Msg As Integer, _
  7.     ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Long  ' Class constructor  Public Sub New()    ' This call is required by the Windows Form Designer    InitializeComponent()    ' Register ourselves to handle clipboard modifications    _nxtCbVwrHWnd = SetClipboardViewer(Handle)  End Sub  Private Sub AddDataToGrid()    Dim currentClipboardData As DataObject = _
  8.       My.Computer.Clipboard.GetDataObject    ' If the clipboard contents are AutoCAD-related    If IsAutoCAD(currentClipboardData.GetFormats) Then      ' Create a new row for our grid and add our clipboard
  9.       ' data stored in the "tag"      Dim newRow As New DataGridViewRow()
  10.       newRow.Tag = currentClipboardData      ' Increment our counter      _clipboardCounter += 1      ' Create and add a cell for the name, using our counter      Dim newNameCell As New DataGridViewTextBoxCell
  11.       newNameCell.Value = "Clipboard " & _clipboardCounter
  12.       newRow.Cells.Add(newNameCell)      ' Get the current time and place that in another cell      Dim newTimeCell As New DataGridViewTextBoxCell
  13.       newTimeCell.Value = Now.ToLongTimeString
  14.       newRow.Cells.Add(newTimeCell)      ' Add our row to the data grid and select it      clipboardDataGridView.Rows.Add(newRow)
  15.       clipboardDataGridView.FirstDisplayedScrollingRowIndex = _
  16.         clipboardDataGridView.Rows.Count - 1
  17.       newRow.Selected = True    End If  End Sub  ' Move the selected item's data into the clipboard  ' Check whether the clipboard data was created by AutoCAD  Private Function IsAutoCAD(ByVal Formats As String()) As Boolean    For Each item As String In Formats
  18.       If item.Contains("AutoCAD") Then Return True
  19.     Next
  20.     Return False  End Function  Private Sub PasteToClipboard()    ' Use a variable to make sure we don't edit the
  21.     ' clipboard contents at the wrong time    _internalHold = True
  22.     My.Computer.Clipboard.SetDataObject( _
  23.       clipboardDataGridView.SelectedRows.Item(0).Tag)
  24.     _internalHold = False  End Sub  ' Send a command to AutoCAD  Private Sub SendAutoCADCommand(ByVal cmd As String)    AcApp.DocumentManager.MdiActiveDocument.SendStringToExecute( _
  25.       cmd, True, False, True)  End Sub  ' Our context-menu command handlers  Private Sub PasteToolStripButton_Click( _
  26.     ByVal sender As Object, ByVal e As EventArgs) _
  27.     Handles PasteToolStripMenuItem.Click    ' Swap the data from the selected item in the grid into the
  28.     ' clipboard and use the internal AutoCAD command to paste it    If clipboardDataGridView.SelectedRows.Count = 1 Then
  29.       PasteToClipboard()
  30.       SendAutoCADCommand("_pasteclip ")
  31.     End If
  32.   End Sub  Private Sub PasteAsBlockToolStripMenuItem_Click( _
  33.     ByVal sender As Object, ByVal e As EventArgs) _
  34.     Handles PasteAsBlockToolStripMenuItem.Click    ' Swap the data from the selected item in the grid into the
  35.     ' clipboard and use the internal AutoCAD command to paste it
  36.     ' as a block    If clipboardDataGridView.SelectedRows.Count = 1 Then
  37.       PasteToClipboard()
  38.       SendAutoCADCommand("_pasteblock ")
  39.     End If
  40.   End Sub  Private Sub PasteToOriginalCoordinatesToolStripMenuItem_Click( _
  41.     ByVal sender As Object, ByVal e As EventArgs) _
  42.     Handles PasteToOriginalCoordinatesToolStripMenuItem.Click    ' Swap the data from the selected item in the grid into the
  43.     ' clipboard and use the internal AutoCAD command to paste it
  44.     ' at the original location    If clipboardDataGridView.SelectedRows.Count = 1 Then
  45.       PasteToClipboard()
  46.       SendAutoCADCommand("_pasteorig ")
  47.     End If
  48.   End Sub  Private Sub RemoveAllToolStripButton_Click( _
  49.     ByVal sender As Object, ByVal e As EventArgs) _
  50.     Handles RemoveAllToolStripButton.Click    ' Remove all the items in the grid    clipboardDataGridView.Rows.Clear()
  51.   End Sub  Private Sub RenameToolStripMenuItem_Click( _
  52.     ByVal sender As Object, ByVal e As EventArgs) _
  53.     Handles RenameToolStripMenuItem.Click    ' Rename the selected row by editing the name cell    If clipboardDataGridView.SelectedRows.Count = 1 Then
  54.       clipboardDataGridView.BeginEdit(True)
  55.     End If
  56.   End Sub  Private Sub RemoveToolStripMenuItem_Click( _
  57.     ByVal sender As Object, ByVal e As EventArgs) _
  58.     Handles RemoveToolStripMenuItem.Click    ' Remove the selected grid item    If clipboardDataGridView.SelectedRows.Count = 1 Then
  59.       clipboardDataGridView.Rows.Remove( _
  60.         clipboardDataGridView.SelectedRows.Item(0))
  61.     End If
  62.   End Sub  ' Our grid view event handlers  Private Sub ClipboardDataGridView_CellMouseDown( _
  63.     ByVal sender As Object, _
  64.     ByVal e As DataGridViewCellMouseEventArgs) _
  65.     Handles clipboardDataGridView.CellMouseDown    ' Responding to this event allows us to make sure the
  66.     ' correct row is properly selected on right-click    If e.Button = Windows.Forms.MouseButtons.Right Then
  67.       clipboardDataGridView.CurrentCell = _
  68.         clipboardDataGridView.Item(e.ColumnIndex, e.RowIndex)
  69.     End If
  70.   End Sub  Private Sub ClipboardDataGridView_MouseDown( _
  71.     ByVal sender As System.Object, ByVal e As MouseEventArgs) _
  72.     Handles clipboardDataGridView.MouseDown    ' On right-click display the row as selected and show
  73.     ' the context menu at the location of the cursor    If e.Button = Windows.Forms.MouseButtons.Right Then
  74.       Dim hti As DataGridView.HitTestInfo = _
  75.         clipboardDataGridView.HitTest(e.X, e.Y)
  76.       If hti.Type = DataGridViewHitTestType.Cell Then        clipboardDataGridView.ClearSelection()
  77.         clipboardDataGridView.Rows(hti.RowIndex).Selected = True        ContextMenuStrip.Show(clipboardDataGridView, e.Location)
  78.       End If
  79.     End If  End Sub  ' Override WndProc to get messages  Protected Overrides Sub WndProc(ByRef m As Message)
  80.     Select Case m.Msg  ' The clipboard has changed  Case Is = WM_DRAWCLIPBOARD    If Not _internalHold Then AddDataToGrid()    SendMessage(_nxtCbVwrHWnd, m.Msg, m.WParam, m.LParam)    ' Another clipboard viewer has removed itself  Case Is = WM_CHANGECBCHAIN    If m.WParam = CType(_nxtCbVwrHWnd, IntPtr) Then
  81.       _nxtCbVwrHWnd = m.LParam
  82.     Else
  83.       SendMessage(_nxtCbVwrHWnd, m.Msg, m.WParam, m.LParam)
  84.     End If    End Select    MyBase.WndProc(m)
  85.   End SubEnd ClassPublic Class PaletteToolStrip  Inherits ToolStrip  Public Sub New()
  86.     MyBase.New()
  87.   End Sub  Public Sub New(ByVal ParamArray Items() As ToolStripItem)
  88.     MyBase.New(Items)
  89.   End Sub  Protected Overrides Sub WndProc(ByRef m As Message)
  90.     If m.Msg = &H21 AndAlso CanFocus AndAlso Not Focused Then
  91.       Focus()
  92.     End If
  93.     MyBase.WndProc(m)
  94.   End SubEnd Class
I also added a VB.NET version of the C# code that automatically registers an AutoCAD .NET application for demand-loading based on the commands it defines:
  1. Imports System.Collections.Generic
  2. Imports System.Reflection
  3. Imports System.Resources
  4. Imports System
  5. Imports Microsoft.Win32
  6. Imports Autodesk.AutoCAD.DatabaseServices
  7. Imports Autodesk.AutoCAD.RuntimeNamespace DemandLoading
  8.   Public Class RegistryUpdate
  9.     Public Shared Sub RegisterForDemandLoading()
  10.   ' Get the assembly, its name and location  Dim assem As Assembly = Assembly.GetExecutingAssembly()
  11.   Dim name As String = assem.GetName().Name
  12.   Dim path As String = assem.Location  ' We'll collect information on the commands
  13.   ' (we could have used a map or a more complex
  14.   ' container for the global and localized names
  15.   ' - the assumption is we will have an equal
  16.   ' number of each with possibly fewer groups)  Dim globCmds As New List(Of String)()
  17.   Dim locCmds As New List(Of String)()
  18.   Dim groups As New List(Of String)()  ' Iterate through the modules in the assembly  Dim mods As [Module]() = assem.GetModules(True)
  19.   For Each [mod] As [Module] In mods
  20.     ' Within each module, iterate through the types    Dim types As Type() = [mod].GetTypes()
  21.     For Each type As Type In types
  22.       ' We may need to get a type's resources      Dim rm As New ResourceManager(type.FullName, assem)
  23.       rm.IgnoreCase = True      ' Get each method on a type      Dim meths As MethodInfo() = type.GetMethods()
  24.       For Each meth As MethodInfo In meths
  25.         ' Get the methods custom command attribute(s)        Dim attbs As Object() = _
  26.           meth.GetCustomAttributes( _
  27.         GetType(CommandMethodAttribute), True)
  28.         For Each attb As Object In attbs
  29.           Dim cma As CommandMethodAttribute = _
  30.             TryCast(attb, CommandMethodAttribute)
  31.           If cma IsNot Nothing Then
  32.             ' And we can finally harvest the information
  33.             ' about each command            Dim globName As String = cma.GlobalName
  34.             Dim locName As String = globName
  35.             Dim lid As String = cma.LocalizedNameId            ' If we have a localized command ID,
  36.             ' let's look it up in our resources            If lid IsNot Nothing Then
  37.               ' Let's put a try-catch block around this
  38.               ' Failure just means we use the global
  39.               ' name twice (the default)              Try
  40.                 locName = rm.GetString(lid)
  41.               Catch
  42.               End Try
  43.             End If            ' Add the information to our data structures            globCmds.Add(globName)
  44.             locCmds.Add(locName)            If cma.GroupName IsNot Nothing AndAlso _
  45.               Not groups.Contains(cma.GroupName) Then
  46.               groups.Add(cma.GroupName)
  47.             End If
  48.           End If
  49.         Next
  50.       Next
  51.     Next
  52.   Next  ' Let's register the application to load on demand (12)
  53.   ' if it contains commands, otherwise we will have it
  54.   ' load on AutoCAD startup (2)  Dim flags As Integer = (If(globCmds.Count > 0, 12, 2))  ' By default let's create the commands in HKCU
  55.   ' (pass false if we want to create in HKLM)  CreateDemandLoadingEntries(name, path, globCmds, locCmds, _
  56.     groups, flags, True)
  57.     End Sub    Public Shared Sub UnregisterForDemandLoading()
  58.       RemoveDemandLoadingEntries(True)
  59.     End Sub    ' Helper functions    Private Shared Sub CreateDemandLoadingEntries( _
  60.       ByVal name As String, ByVal path As String, _
  61.       ByVal globCmds As List(Of String), _
  62.       ByVal locCmds As List(Of String), _
  63.       ByVal groups As List(Of String), _
  64.       ByVal flags As Integer, _
  65.       ByVal currentUser As Boolean)      ' Choose a Registry hive based on the function input      Dim hive As RegistryKey = _
  66.         If(currentUser,Registry.CurrentUser,Registry.LocalMachine)      ' Open the main AutoCAD (or vertical) and "Applications" keys      Dim ack As RegistryKey = _
  67.         hive.OpenSubKey( _
  68.           HostApplicationServices.Current.RegistryProductRootKey)
  69.       Dim appk As RegistryKey = ack.OpenSubKey("Applications", True)      ' Already registered? Just return      Dim subKeys As String() = appk.GetSubKeyNames()
  70.       For Each subKey As String In subKeys
  71.         If subKey.Equals(name) Then
  72.           appk.Close()
  73.           Exit Sub
  74.         End If
  75.       Next      ' Create the our application's root key and its values      Dim rk As RegistryKey = appk.CreateSubKey(name)
  76.       rk.SetValue("DESCRIPTION", name, RegistryValueKind.[String])
  77.       rk.SetValue("LOADCTRLS", flags, RegistryValueKind.DWord)
  78.       rk.SetValue("LOADER", path, RegistryValueKind.[String])
  79.       rk.SetValue("MANAGED", 1, RegistryValueKind.DWord)      ' Create a subkey if there are any commands...      If (globCmds.Count = locCmds.Count) _
  80.         AndAlso globCmds.Count > 0 Then
  81.         Dim ck As RegistryKey = rk.CreateSubKey("Commands")        For i As Integer = 0 To globCmds.Count - 1
  82.           ck.SetValue(globCmds(i), locCmds(i), _
  83.             RegistryValueKind.[String])
  84.         Next
  85.       End If      ' And the command groups, if there are any      If groups.Count > 0 Then
  86.         Dim gk As RegistryKey = rk.CreateSubKey("Groups")        For Each grpName As String In groups
  87.           gk.SetValue(grpName, grpName, _
  88.             RegistryValueKind.[String])
  89.         Next
  90.       End If      appk.Close()
  91.     End Sub    Private Shared Sub RemoveDemandLoadingEntries( _
  92.       ByVal currentUser As Boolean)      Try        ' Choose a Registry hive based on the function input        Dim hive As RegistryKey = _
  93.           If(currentUser,Registry.CurrentUser,Registry.LocalMachine)        ' Open the main AutoCAD (or vertical) and "Applications" keys        Dim ack As RegistryKey = _
  94.           hive.OpenSubKey( _
  95.             HostApplicationServices.Current.RegistryProductRootKey)
  96.         Dim appk As RegistryKey = _
  97.           ack.OpenSubKey("Applications", True)        ' Delete the key with the same name as this assembly        appk.DeleteSubKeyTree( _
  98.           Assembly.GetExecutingAssembly().GetName().Name)
  99.         appk.Close()      Catch
  100.       End Try
  101.     End Sub
  102.   End Class
  103. End Namespace
That’s really all there is to it. If you have any feedback regarding the behaviour of the tool, please do send us an email.
回复

使用道具 举报

72

主题

2726

帖子

9

银币

社区元老

Rank: 75Rank: 75Rank: 75

铜币
3014
发表于 2010-2-3 22:30:00 | 显示全部楼层
二、加强版本的截图
http://through-the-interface.typepad.com/through_the_interface/2009/11/novembers-plugin-of-the-month-screenshot.html
November 16, 2009
Updated version of Screenshot now available
We’ve had a few reports of issues with the Screenshot “Plugin of the Month”. They fall into two main categories:
Attempting to NETLOAD the application DLL from a network share
Within the ReadMe for each of the plugins we’ve documented that each application’s DLL module should be copied to the local file system – preferably inside the AutoCAD Program Files folder – before being loaded by NETLOAD. We recommend this because it essentially stops users from hitting a whole category of .NET Framework-related problems when loading and running the plugins.
If you didn’t heed this advice then you’d probably find that, as soon as the SCREENSHOT command was launched, you received a message such as “FATAL ERROR: Unsupported version of Windows Presentation Foundation.”
Now I don’t have an exhaustive list of reasons it’s best to place .NET DLLs in the AutoCAD root program folder, but my understanding/belief is that it’s down to two main ones:
1. Security
The .NET Framework implements security for different zones, and – up until the .NET Framework 3.5 SP1 – the default security setting for the “Local Intranet” (which affects applications being loaded from network shares) was “Medium Trust”. This level of trust means:
Programs might not be able to access most protected resources such as the registry or security policy settings, or access your local file system without user interaction. Programs will not be able to connect back to their site of origin, resolve domain names, and use all windowing resources.
Our “Plugin of the Month” applications target lower versions of the .NET Framework (we want to avoid forcing people to use the latest version of the framework and want the applications to run – where possible – at least as far back as AutoCAD 2007), and so their default level of trust will make running from a network share a problem.
Now it’s possible to use the Control Panel to configure earlier versions of the .NET Framework to be more tolerant of network-resident DLLs (you can change the trust level for the local intranet zone to be higher), but it’s still not something I’d recommend: I’m pretty sure this is only one aspect of the situation, and it would be dangerous to assume it’s all that’s needed.
2. Assembly Loading
The other main reason for putting modules in AutoCAD’s root program folder is related to the loading of .NET assemblies into AutoCAD’s AppDomain (which is basically what the NETLOAD command does, and this choice of architecture is why there’s no NETUNLOAD command).
While NETLOAD uses Assembly.LoadFrom() to load in .NET assembly DLLs – which does allow you to specify a path other than the current folder – there does appear to be some fragility overall with the location of assemblies and how they reference each other. It’s safest to place assemblies at a location beneath the calling executable (i.e. AutoCAD).
Capturing images with the “force foreground to black” option results in a completely black image
This one is definitely down to me. A big thank you to Harry Kortekaas for very diligently helping me identify the problem.
It actually came down to some poor application logic on my side: I was forgetting to check the “use white background” flag at the right place, and had also inverted the test for being in modelspace vs. paperspace. By chance – in many situations – the white background was picked up correctly from the paperspace, and so the issue wasn’t easily reproducible.
Anyway, a fix has now been integrated into version 1.0.2 of the application, which is now downloadable via Autodesk Labs. I’ve also included an updated version of the code below.

A third type of issue has been reported, but I haven’t yet been able to determine the cause: on one system (meaning: one reported, so far) the file selection dialog and the dynamic input graphics are not being refreshed away in time for the capture to take place.
This is similar to something we’ve been aware of from early on - the fact that the call to Editor.GetFileNameForSave() returns control to the application before the Operating System has had the chance to refresh the screen – so I built a delay (a call to System.Threading.Thread.Sleep()) into the original application to wait for a second (we started at 0.1s and worked our way upwards) which seemed to address it for all the systems upon which the application was tested.
At first it seemed – during the diagnosis of this particular issue – that this delay needed increasing, and so I added it to the per-user application settings (with the default value of 1.0, i.e. a second). This is now configurable via a new command – CONFIGSS – the logic being to keep rarely-used configuration options apart from the common ones accessible via the SCREENSHOT command. In this particular situation, though, no amount of delay seemed to help.
The same person reported an issue with the input box and temporary dimensions displayed during dynamic input not being repainted away on this particular system when the image is placed on the clipboard, so I’ve also introduced a configurable delay there, too. This is also set using CONFIGSS – the default is currently 0 seconds, to replicate the previous behaviour.
I suspect that both issues are actually down to a configuration problem (we’ll hopefully see whether my suspicion is valid), but I’ve left the capability to configure them in the application, in any case. People may also choose to reduce the current delay using CONFIGSS, as one second was on the high end: 0.3 seconds should be enough for the majority of systems. Just think of all the time you can get back!   :-)
If anyone else out there has seen something similar to this with the Screenshot application, please do let us know.
The CONFIGSS command has a third setting exposed (although it’s the first one it prompts for), and this was also introduced after receiving feedback from the same source: it’s sometimes preferred to have a boundary zone or buffer around the extents chosen via the “Objects” option, so that the selection isn’t so tight-fitting around the objects. The application now has a default of 10% of the screen extents’ width or height (whichever is larger) that will get added automatically. To go back to the old behaviour you can configure this percentage to zero using CONFIGSS.
Here’s the updated C# code: the compiled version of which (again, version 1.0.2) is now available:
  1. // (C) Copyright 2009 by Autodesk, Inc.
  2. //
  3. // Permission to use, copy, modify, and distribute this software in
  4. // object code form for any purpose and without fee is hereby granted,
  5. // provided that the above copyright notice appears in all copies and
  6. // that both that copyright notice and the limited warranty and
  7. // restricted rights notice below appear in all supporting
  8. // documentation.
  9. //
  10. // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
  11. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
  12. // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
  13. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
  14. // UNINTERRUPTED OR ERROR FREE.
  15. //
  16. // Use, duplication, or disclosure by the U.S. Government is subject to
  17. // restrictions set forth in FAR 52.227-19 (Commercial Computer
  18. // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
  19. // (Rights in Technical Data and Computer Software), as applicable.
  20. //
  21. using Autodesk.AutoCAD.ApplicationServices;
  22. using Autodesk.AutoCAD.DatabaseServices;
  23. using Autodesk.AutoCAD.EditorInput;
  24. using Autodesk.AutoCAD.Geometry;
  25. using Autodesk.AutoCAD.GraphicsInterface;
  26. using Autodesk.AutoCAD.GraphicsSystem;
  27. using Autodesk.AutoCAD.Runtime;
  28. using Autodesk.AutoCAD.Colors;
  29. using System.Drawing.Imaging;
  30. using System.Drawing.Printing;
  31. using System.Drawing.Drawing2D;
  32. using System.Drawing;
  33. using System.Runtime.InteropServices;
  34. using System.Collections;
  35. using System.Configuration;
  36. using System;
  37. using DemandLoading;
  38. namespace Screenshot
  39. {
  40.   public class ScreenshotApplication : IExtensionApplication
  41.   {
  42.     // Define a class for our custom data
  43.     public class AppData : ApplicationSettingsBase
  44.     {
  45.       [UserScopedSetting()]
  46.       [DefaultSettingValue("true")]
  47.       public bool Clipboard
  48.       {
  49.         get { return ((bool)this["Clipboard"]); }
  50.         set { this["Clipboard"] = (bool)value; }
  51.       }
  52.       [UserScopedSetting()]
  53.       [DefaultSettingValue("false")]
  54.       public bool Print
  55.       {
  56.         get { return ((bool)this["Print"]); }
  57.         set { this["Print"] = (bool)value; }
  58.       }
  59.       [UserScopedSetting()]
  60.       [DefaultSettingValue("false")]
  61.       public bool WhiteBackground
  62.       {
  63.         get { return ((bool)this["WhiteBackground"]); }
  64.         set { this["WhiteBackground"] = (bool)value; }
  65.       }
  66.       [UserScopedSetting()]
  67.       [DefaultSettingValue("false")]
  68.       public bool BlackForeground
  69.       {
  70.         get { return ((bool)this["BlackForeground"]); }
  71.         set { this["BlackForeground"] = (bool)value; }
  72.       }
  73.       [UserScopedSetting()]
  74.       [DefaultSettingValue("false")]
  75.       public bool Grayscale
  76.       {
  77.         get { return ((bool)this["Grayscale"]); }
  78.         set { this["Grayscale"] = (bool)value; }
  79.       }
  80.       [UserScopedSetting()]
  81.       [DefaultSettingValue("0.1")]
  82.       public double ExtentsScale
  83.       {
  84.         get { return ((double)this["ExtentsScale"]); }
  85.         set { this["ExtentsScale"] = (double)value; }
  86.       }
  87.       [UserScopedSetting()]
  88.       [DefaultSettingValue("1.0")]
  89.       public double FileCaptureDelay
  90.       {
  91.         get { return ((double)this["FileCaptureDelay"]); }
  92.         set { this["FileCaptureDelay"] = (double)value; }
  93.       }
  94.       [UserScopedSetting()]
  95.       [DefaultSettingValue("0.0")]
  96.       public double ClipboardCaptureDelay
  97.       {
  98.         get { return ((double)this["ClipboardCaptureDelay"]); }
  99.         set { this["ClipboardCaptureDelay"] = (double)value; }
  100.       }
  101.     }
  102.     // A struct for communicating colours to/from AutoCAD
  103.     public struct AcColorSettings
  104.     {
  105.       public UInt32 dwGfxModelBkColor;
  106.       public UInt32 dwGfxLayoutBkColor;
  107.       public UInt32 dwParallelBkColor;
  108.       public UInt32 dwBEditBkColor;
  109.       public UInt32 dwCmdLineBkColor;
  110.       public UInt32 dwPlotPrevBkColor;
  111.       public UInt32 dwSkyGradientZenithColor;
  112.       public UInt32 dwSkyGradientHorizonColor;
  113.       public UInt32 dwGroundGradientOriginColor;
  114.       public UInt32 dwGroundGradientHorizonColor;
  115.       public UInt32 dwEarthGradientAzimuthColor;
  116.       public UInt32 dwEarthGradientHorizonColor;
  117.       public UInt32 dwModelCrossHairColor;
  118.       public UInt32 dwLayoutCrossHairColor;
  119.       public UInt32 dwParallelCrossHairColor;
  120.       public UInt32 dwPerspectiveCrossHairColor;
  121.       public UInt32 dwBEditCrossHairColor;
  122.       public UInt32 dwParallelGridMajorLines;
  123.       public UInt32 dwPerspectiveGridMajorLines;
  124.       public UInt32 dwParallelGridMinorLines;
  125.       public UInt32 dwPerspectiveGridMinorLines;
  126.       public UInt32 dwParallelGridAxisLines;
  127.       public UInt32 dwPerspectiveGridAxisLines;
  128.       public UInt32 dwTextForeColor;
  129.       public UInt32 dwTextBkColor;
  130.       public UInt32 dwCmdLineForeColor;
  131.       public UInt32 dwAutoTrackingVecColor;
  132.       public UInt32 dwLayoutATrackVecColor;
  133.       public UInt32 dwParallelATrackVecColor;
  134.       public UInt32 dwPerspectiveATrackVecColor;
  135.       public UInt32 dwBEditATrackVecColor;
  136.       public UInt32 dwModelASnapMarkerColor;
  137.       public UInt32 dwLayoutASnapMarkerColor;
  138.       public UInt32 dwParallelASnapMarkerColor;
  139.       public UInt32 dwPerspectiveASnapMarkerColor;
  140.       public UInt32 dwBEditASnapMarkerColor;
  141.       public UInt32 dwModelDftingTooltipColor;
  142.       public UInt32 dwLayoutDftingTooltipColor;
  143.       public UInt32 dwParallelDftingTooltipColor;
  144.       public UInt32 dwPerspectiveDftingTooltipColor;
  145.       public UInt32 dwBEditDftingTooltipColor;
  146.       public UInt32 dwModelDftingTooltipBkColor;
  147.       public UInt32 dwLayoutDftingTooltipBkColor;
  148.       public UInt32 dwParallelDftingTooltipBkColor;
  149.       public UInt32 dwPerspectiveDftingTooltipBkColor;
  150.       public UInt32 dwBEditDftingTooltipBkColor;
  151.       public UInt32 dwModelLightGlyphs;
  152.       public UInt32 dwLayoutLightGlyphs;
  153.       public UInt32 dwParallelLightGlyphs;
  154.       public UInt32 dwPerspectiveLightGlyphs;
  155.       public UInt32 dwBEditLightGlyphs;
  156.       public UInt32 dwModelLightHotspot;
  157.       public UInt32 dwLayoutLightHotspot;
  158.       public UInt32 dwParallelLightHotspot;
  159.       public UInt32 dwPerspectiveLightHotspot;
  160.       public UInt32 dwBEditLightHotspot;
  161.       public UInt32 dwModelLightFalloff;
  162.       public UInt32 dwLayoutLightFalloff;
  163.       public UInt32 dwParallelLightFalloff;
  164.       public UInt32 dwPerspectiveLightFalloff;
  165.       public UInt32 dwBEditLightFalloff;
  166.       public UInt32 dwModelLightStartLimit;
  167.       public UInt32 dwLayoutLightStartLimit;
  168.       public UInt32 dwParallelLightStartLimit;
  169.       public UInt32 dwPerspectiveLightStartLimit;
  170.       public UInt32 dwBEditLightStartLimit;
  171.       public UInt32 dwModelLightEndLimit;
  172.       public UInt32 dwLayoutLightEndLimit;
  173.       public UInt32 dwParallelLightEndLimit;
  174.       public UInt32 dwPerspectiveLightEndLimit;
  175.       public UInt32 dwBEditLightEndLimit;
  176.       public UInt32 dwModelCameraGlyphs;
  177.       public UInt32 dwLayoutCameraGlyphs;
  178.       public UInt32 dwParallelCameraGlyphs;
  179.       public UInt32 dwPerspectiveCameraGlyphs;
  180.       public UInt32 dwModelCameraFrustrum;
  181.       public UInt32 dwLayoutCameraFrustrum;
  182.       public UInt32 dwParallelCameraFrustrum;
  183.       public UInt32 dwPerspectiveCameraFrustrum;
  184.       public UInt32 dwModelCameraClipping;
  185.       public UInt32 dwLayoutCameraClipping;
  186.       public UInt32 dwParallelCameraClipping;
  187.       public UInt32 dwPerspectiveCameraClipping;
  188.       public int nModelCrosshairUseTintXYZ;
  189.       public int nLayoutCrosshairUseTintXYZ;
  190.       public int nParallelCrosshairUseTintXYZ;
  191.       public int nPerspectiveCrosshairUseTintXYZ;
  192.       public int nBEditCrossHairUseTintXYZ;
  193.       public int nModelATrackVecUseTintXYZ;
  194.       public int nLayoutATrackVecUseTintXYZ;
  195.       public int nParallelATrackVecUseTintXYZ;
  196.       public int nPerspectiveATrackVecUseTintXYZ;
  197.       public int nBEditATrackVecUseTintXYZ;
  198.       public int nModelDftingTooltipBkUseTintXYZ;
  199.       public int nLayoutDftingTooltipBkUseTintXYZ;
  200.       public int nParallelDftingTooltipBkUseTintXYZ;
  201.       public int nPerspectiveDftingTooltipBkUseTintXYZ;
  202.       public int nBEditDftingTooltipBkUseTintXYZ;
  203.       public int nParallelGridMajorLineTintXYZ;
  204.       public int nPerspectiveGridMajorLineTintXYZ;
  205.       public int nParallelGridMinorLineTintXYZ;
  206.       public int nPerspectiveGridMinorLineTintXYZ;
  207.       public int nParallelGridAxisLineTintXYZ;
  208.       public int nPerspectiveGridAxisLineTintXYZ;
  209.     };
  210.     // For the coordinate tranformation we need...  
  211.     // A Win32 function:
  212.     [DllImport("user32.dll")]
  213.     static extern bool ClientToScreen(IntPtr hWnd, ref Point pt);
  214.     // And to access the colours in AutoCAD, we need ObjectARX...
  215.     [DllImport("acad.exe",
  216.     CallingConvention = CallingConvention.Cdecl,
  217.     EntryPoint = "?acedGetCurrentColors@@YAHPAUAcColorSettings@@@Z"
  218.     )]
  219.     static extern bool acedGetCurrentColors32(
  220.       out AcColorSettings colorSettings
  221.     );
  222.     [DllImport("acad.exe",
  223.     CallingConvention = CallingConvention.Cdecl,
  224.     EntryPoint = "?acedSetCurrentColors@@YAHPAUAcColorSettings@@@Z"
  225.     )]
  226.     static extern bool acedSetCurrentColors32(
  227.       ref AcColorSettings colorSettings
  228.     );
  229.     // 64-bit versions of these functions...
  230.     [DllImport("acad.exe",
  231.     CallingConvention = CallingConvention.Cdecl,
  232.     EntryPoint = "?acedGetCurrentColors@@YAHPEAUAcColorSettings@@@Z"
  233.     )]
  234.     static extern bool acedGetCurrentColors64(
  235.       out AcColorSettings colorSettings
  236.     );
  237.     [DllImport("acad.exe",
  238.     CallingConvention = CallingConvention.Cdecl,
  239.     EntryPoint = "?acedSetCurrentColors@@YAHPEAUAcColorSettings@@@Z"
  240.     )]
  241.     static extern bool acedSetCurrentColors64(
  242.       ref AcColorSettings colorSettings
  243.     );
  244.     // Helper functions that call automatically to 32- or 64-bit
  245.     // versions, as appropriate
  246.     static bool acedGetCurrentColors(
  247.       out AcColorSettings colorSettings
  248.     )
  249.     {
  250.       if (IntPtr.Size > 4)
  251.         return acedGetCurrentColors64(out colorSettings);
  252.       else
  253.         return acedGetCurrentColors32(out colorSettings);
  254.     }
  255.     static bool acedSetCurrentColors(
  256.       ref AcColorSettings colorSettings
  257.     )
  258.     {
  259.       if (IntPtr.Size > 4)
  260.         return acedSetCurrentColors64(ref colorSettings);
  261.       else
  262.         return acedSetCurrentColors32(ref colorSettings);
  263.     }
  264.     // IExtensionApplication protocol
  265.     public void Initialize()
  266.     {
  267.       try
  268.       {
  269.         RegistryUpdate.RegisterForDemandLoading();
  270.       }
  271.       catch
  272.       { }
  273.     }
  274.     public void Terminate()
  275.     {
  276.     }
  277.     [CommandMethod("ADNPLUGINS", "REMOVESS", CommandFlags.Modal)]
  278.     static public void RemoveScreenshot()
  279.     {
  280.       RegistryUpdate.UnregisterForDemandLoading();
  281.     }
  282.     [CommandMethod("ADNPLUGINS", "CONFIGSS", CommandFlags.Modal)]
  283.     static public void ConfigureScreenshot()
  284.     {
  285.       // An additional command for some "advanced" configuration
  286.       // options
  287.       Document doc =
  288.         Application.DocumentManager.MdiActiveDocument;
  289.       Editor ed = doc.Editor;
  290.       // Retrieve our application settings (or create new ones)
  291.       AppData ad = new AppData();
  292.       ad.Reload();
  293.       if (ad != null)
  294.       {
  295.         // Ask the user for the percentage increase to apply to
  296.         // the extents determined by the Objects option
  297.         PromptIntegerOptions pio =
  298.           new PromptIntegerOptions(
  299.             "\nPercentage increase when capturing " +
  300.             "object extents: "
  301.           );
  302.         pio.DefaultValue = (int)(ad.ExtentsScale * 100);
  303.         pio.LowerLimit = 0;
  304.         pio.UpperLimit = 100;
  305.         pio.UseDefaultValue = true;
  306.         PromptIntegerResult pir = ed.GetInteger(pio);
  307.         if (pir.Status != PromptStatus.OK)
  308.           return;
  309.         ad.ExtentsScale = pir.Value * 0.01;
  310.         // Ask the use for the delay to apply after a file
  311.         // has been selected, to allow the OS to redraw their
  312.         // screen graphics
  313.         PromptDoubleOptions pdo =
  314.           new PromptDoubleOptions(
  315.             "\nDelay in seconds to allow " +
  316.             "repaint after file selection: "
  317.           );
  318.         pdo.DefaultValue = ad.FileCaptureDelay;
  319.         pdo.AllowNegative = false;
  320.         pdo.UseDefaultValue = true;
  321.         PromptDoubleResult pdr = ed.GetDouble(pdo);
  322.         if (pdr.Status != PromptStatus.OK)
  323.           return;
  324.         ad.FileCaptureDelay = pdr.Value;
  325.         // Ask the user for the delay to apply before a
  326.         // clipboard capture to allow any dynamic
  327.         // input graphics to be undrawn
  328.         pdo.Message =
  329.           "\nDelay in seconds to allow " +
  330.           "repaint before clipboard selection: ";
  331.         pdo.DefaultValue = ad.ClipboardCaptureDelay;
  332.         pdr = ed.GetDouble(pdo);
  333.         if (pdr.Status != PromptStatus.OK)
  334.           return;
  335.         ad.ClipboardCaptureDelay = pdr.Value;
  336.         ad.Save();
  337.       }
  338.     }
  339.     // Command to capture the main and active drawing windows
  340.     // or a user-selected portion of a drawing
  341.     [CommandMethod("ADNPLUGINS", "SCREENSHOT", CommandFlags.Modal)]
  342.     static public void CaptureScreenShot()
  343.     {
  344.       Document doc =
  345.         Application.DocumentManager.MdiActiveDocument;
  346.       Editor ed = doc.Editor;
  347.       // Retrieve our application settings (or create new ones)
  348.       AppData ad = new AppData();
  349.       ad.Reload();
  350.       if (ad != null)
  351.       {
  352.         string filename = "";
  353.         bool settingschosen;
  354.         PromptPointResult ppr;
  355.         do
  356.         {
  357.           settingschosen = false;
  358.           // Ask the user for the screen window to capture
  359.           PrintSettings(ed, ad);
  360.           PromptPointOptions ppo =
  361.             new PromptPointOptions(
  362.               "\nSelect first point of capture window or " +
  363.               "[Document/Application/Objects/Settings]: ",
  364.               "Document Application Objects Settings"
  365.             );
  366.           // Get the first point of the capture window,
  367.           // or a keyword
  368.           ppr = ed.GetPoint(ppo);
  369.           if (ppr.Status == PromptStatus.Keyword)
  370.           {
  371.             if (ppr.StringResult == "Document")
  372.             {
  373.               // Capture the active document window
  374.               filename = PauseOrFilename(ed, ad);
  375.               ScreenShotToFile(
  376.                 Application.DocumentManager.
  377.                   MdiActiveDocument.Window,
  378.                 30, 26, 10, 10,
  379.                 filename,
  380.                 ad
  381.               );
  382.             }
  383.             else if (ppr.StringResult == "Application")
  384.             {
  385.               // Capture the entire application window
  386.               filename = PauseOrFilename(ed, ad);
  387.               ScreenShotToFile(
  388.                 Application.MainWindow,
  389.                 0, 0, 0, 0,
  390.                 filename,
  391.                 ad
  392.               );
  393.             }
  394.             else if (ppr.StringResult == "Objects")
  395.             {
  396.               // Ask the user to select a number of entities
  397.               PromptSelectionResult psr =
  398.                 ed.GetSelection();
  399.               if (psr.Status == PromptStatus.OK)
  400.               {
  401.                 // Regenerate to clear any selection highlighting
  402.                 ed.WriteMessage("\n");
  403.                 ed.Regen();
  404.                 // Generate screen coordinate points based on the
  405.                 // drawing points selected
  406.                 // First we get the viewport number
  407.                 short vp =
  408.                   (short)Application.GetSystemVariable("CVPORT");
  409.                 // Then the handle to the current drawing window
  410.                 IntPtr hWnd = doc.Window.Handle;
  411.                 // Get the screen extents of the selected entities
  412.                 Point pt1, pt2;
  413.                 GetExtentsOfSelection(
  414.                   ed, doc, hWnd, vp, psr.Value, out pt1, out pt2
  415.                 );
  416.                 ApplyScaleToExtents(ad.ExtentsScale,ref pt1,ref pt2);
  417.                 // Now save this portion of our screen as a raster
  418.                 // image
  419.                 filename = PauseOrFilename(ed, ad);
  420.                 ScreenShotToFile(pt1, pt2, filename, ad);
  421.               }
  422.             }
  423.             else if (ppr.StringResult == "Settings")
  424.             {
  425.               if (GetSettings(ed, ad))
  426.                 ad.Save();
  427.               settingschosen = true;
  428.             }
  429.           }
  430.         }
  431.         while (settingschosen); // Loop if settings were modified
  432.         if (ppr.Status == PromptStatus.OK)
  433.         {
  434.           // Now we're ready to select the second point
  435.           Point3d first = ppr.Value;
  436.           ppr =
  437.             ed.GetCorner(
  438.               "\nSelect second point of capture window: ",
  439.               first
  440.             );
  441.           if (ppr.Status != PromptStatus.OK)
  442.             return;
  443.           Point3d second = ppr.Value;
  444.           // Generate screen coordinate points based on the
  445.           // drawing points selected
  446.           Point pt1, pt2;
  447.           // First we get the viewport number
  448.           short vp =
  449.             (short)Application.GetSystemVariable("CVPORT");
  450.           // Then the handle to the current drawing window
  451.           IntPtr hWnd = doc.Window.Handle;
  452.           // Now calculate the selected corners in screen coordinates
  453.           pt1 = ScreenFromDrawingPoint(ed, hWnd, first, vp, true);
  454.           pt2 = ScreenFromDrawingPoint(ed, hWnd, second, vp, true);
  455.           // Now save this portion of our screen as a raster image
  456.           filename = PauseOrFilename(ed, ad);
  457.           ScreenShotToFile(pt1, pt2, filename, ad);
  458.         }
  459.       }
  460.     }
  461.     // If using the clipboard let's introduce a pause to allow
  462.     // any dynamic input graphics to be refreshed away.
  463.     // Otherwise get the filename (which will have its own delay)
  464.     private static string PauseOrFilename(Editor ed, AppData ad)
  465.     {
  466.       if (ad.Clipboard)
  467.       {
  468.         ed.UpdateScreen();
  469.         System.Threading.Thread.Sleep(
  470.           (int)(1000 * ad.ClipboardCaptureDelay)
  471.         );
  472.         return "";
  473.       }
  474.       else
  475.         return GetFileName(ed, ad);
  476.     }
  477.     // Iterate through a selection-set and get the overall extents
  478.     // of the various objects relative to the screen
  479.     // (this is imperfect: our extents in WCS may not translate to
  480.     // the extents on the screen. A more thorough approach would be
  481.     // to get a number of points from an object and check each)
  482.     private static void GetExtentsOfSelection(
  483.       Editor ed,
  484.       Document doc,
  485.       IntPtr hWnd,
  486.       short vp,
  487.       SelectionSet ss,
  488.       out Point min,
  489.       out Point max
  490.     )
  491.     {
  492.       // Create minimum and maximum points for the "on screen"
  493.       // extents of our objects
  494.       min = new Point();
  495.       max = new Point();
  496.       // Know which is the first pass through
  497.       bool first = true;
  498.       // Some variables to store transformation results
  499.       Point pt1 = new Point(), pt2 = new Point();
  500.       Transaction tr =
  501.         doc.TransactionManager.StartTransaction();
  502.       using (tr)
  503.       {
  504.         foreach (SelectedObject so in ss)
  505.         {
  506.           DBObject obj =
  507.             tr.GetObject(so.ObjectId, OpenMode.ForRead);
  508.           Entity ent = obj as Entity;
  509.           if (ent != null)
  510.           {
  511.             // Get the WCS extents of each object
  512.             Extents3d ext = ent.GeometricExtents;
  513.             // Calculate the extent corners in screen coordinates
  514.             // (this may not be the true screen extents, but we'll
  515.             // hope it's good enough)
  516.             pt1 =
  517.               ScreenFromDrawingPoint(
  518.                 ed, hWnd, ext.MinPoint, vp, false
  519.               );
  520.             pt2 =
  521.               ScreenFromDrawingPoint(
  522.                 ed, hWnd, ext.MaxPoint, vp, false
  523.               );
  524.             // The points may not be ordered, so get the min and max
  525.             // values for both X and Y from both points
  526.             int minX = Math.Min(pt1.X, pt2.X);
  527.             int minY = Math.Min(pt1.Y, pt2.Y);
  528.             int maxX = Math.Max(pt1.X, pt2.X);
  529.             int maxY = Math.Max(pt1.Y, pt2.Y);
  530.             // On the first run through, just get the points
  531.             if (first)
  532.             {
  533.               min = new Point(minX, minY);
  534.               max = new Point(maxX, maxY);
  535.               first = false;
  536.             }
  537.             else
  538.             {
  539.               // On subsequent runs through, we need to compare
  540.               if (minX  max.X) max.X = maxX;
  541.               if (maxY > max.Y) max.Y = maxY;
  542.             }
  543.           }
  544.         }
  545.         tr.Commit();
  546.       }
  547.     }
  548.     // Apply a scale to the supplied extents
  549.     // (provided as a potion of the extents, i.e. 10% == 0.1)
  550.     private static void ApplyScaleToExtents(
  551.       double factor,
  552.       ref Point pt1,
  553.       ref Point pt2
  554.     )
  555.     {
  556.       // Get the width and height of the selected screen area
  557.       int width = Math.Abs(pt2.X - pt1.X);
  558.       int height = Math.Abs(pt2.Y - pt1.Y);
  559.       // Decide what the (uniform) border should be: use
  560.       // a portion of either the width or the height,
  561.       // whichever's larger
  562.       int border =
  563.         (int)(factor * (width > height ? width : height));
  564.       // Adjust the two screen points by this border amount
  565.       if (pt1.X  e.MarginBounds.Height)
  566.                     {
  567.                       // Change the height to fit the paper
  568.                       hgt = e.MarginBounds.Height;
  569.                       // Adjust the width to maintain scale
  570.                       wid = (int)(ratio * hgt);
  571.                     }
  572.                     // Set the interpolation settings to high
  573.                     // quality
  574.                     e.Graphics.InterpolationMode =
  575.                       InterpolationMode.HighQualityBicubic;
  576.                     // And send the image out to the page
  577.                     e.Graphics.DrawImage(
  578.                       toPrint,
  579.                       e.MarginBounds.X,
  580.                       e.MarginBounds.Y,
  581.                       wid,
  582.                       hgt
  583.                     );
  584.                   };
  585.                 // Create and show the print dialog
  586.                 System.Windows.Forms.PrintDialog pdlg =
  587.                   new System.Windows.Forms.PrintDialog();
  588.                 pdlg.Document = pdoc;
  589.                 if (pdlg.ShowDialog() ==
  590.                     System.Windows.Forms.DialogResult.OK)
  591.                   pdoc.Print(); // Print on OK
  592.               }
  593.             }
  594.           }
  595.         }
  596.         if (ad.WhiteBackground)
  597.         {
  598.           if (vtrId != ObjectId.Null || sbId != ObjectId.Null)
  599.           {
  600.             Remove3DBackground(db, tr, vtrId, sbId);
  601.           }
  602.           else
  603.           {
  604.             if (gotSettings)
  605.             {
  606.               acedSetCurrentColors(ref ocs);
  607.               ed.WriteMessage("\n");
  608.               ed.Regen();
  609.             }
  610.           }
  611.           ed.UpdateScreen();
  612.         }
  613.         tr.Commit();
  614.       }
  615.     }
  616.     // Check whether the active viewport is 3D
  617.     private static bool is3D(Manager gsm)
  618.     {
  619.       short vp =
  620.         (short)Application.GetSystemVariable("CVPORT");
  621.       View v = gsm.GetGsView(vp, false);
  622.       using (v)
  623.       {
  624.         return (v != null);
  625.       }
  626.     }
  627.     // Return the image format to use for a particular filename
  628.     private static ImageFormat GetFormatForFile(string filename)
  629.     {
  630.       // If all else fails, let's create a PNG
  631.       // (might also choose to throw an exception)
  632.       ImageFormat imf = ImageFormat.Png;
  633.       if (filename.Contains("."))
  634.       {
  635.         // Get the filename's extension (what follows the last ".")
  636.         string ext =
  637.           filename.Substring(filename.LastIndexOf(".") + 1);
  638.         // Get the first three characters of the extension
  639.         if (ext.Length > 3)
  640.           ext = ext.Substring(0, 3);
  641.         // Choose the format based on the extension (in lowercase)
  642.         switch (ext.ToLower())
  643.         {
  644.           case "bmp":
  645.             imf = ImageFormat.Bmp;
  646.             break;
  647.           case "gif":
  648.             imf = ImageFormat.Gif;
  649.             break;
  650.           case "jpg":
  651.             imf = ImageFormat.Jpeg;
  652.             break;
  653.           case "tif":
  654.             imf = ImageFormat.Tiff;
  655.             break;
  656.           case "wmf":
  657.             imf = ImageFormat.Wmf;
  658.             break;
  659.           default:
  660.             imf = ImageFormat.Png;
  661.             break;
  662.         }
  663.       }
  664.       return imf;
  665.     }
  666.     // Set the background colour of a 3D view
  667.     private static void Set3DBackground(
  668.       Editor ed,
  669.       Database db,
  670.       Transaction tr,
  671.       EntityColor ec,
  672.       out ObjectId vtrId,
  673.       out ObjectId sbId
  674.     )
  675.     {
  676.       // We're be returning IDs of the Viewport Table Record
  677.       // and of the background itself
  678.       vtrId = ObjectId.Null;
  679.       sbId = ObjectId.Null;
  680.       ed.UpdateTiledViewportsInDatabase();
  681.       ViewportTable vt =
  682.         (ViewportTable)tr.GetObject(
  683.           db.ViewportTableId,
  684.           OpenMode.ForRead
  685.         );
  686.       if (vt.Has("*Active"))
  687.       {
  688.         // Let's get the Viewport Table Record
  689.         vtrId = vt["*Active"];
  690.         DBDictionary nod =
  691.           (DBDictionary)tr.GetObject(
  692.             db.NamedObjectsDictionaryId,
  693.             OpenMode.ForRead
  694.           );
  695.         // And create the background dictionary, if none exists
  696.         ObjectId bkdId = ObjectId.Null;
  697.         DBDictionary bkDict = null;
  698.         const string dictKey = "ACAD_BACKGROUND";
  699.         const string bkKey = "ADNPlugin_Screenshot";
  700.         if (nod.Contains(dictKey))
  701.         {
  702.           bkdId = nod.GetAt(dictKey);
  703.           bkDict =
  704.             (DBDictionary)tr.GetObject(bkdId, OpenMode.ForWrite);
  705.         }
  706.         else
  707.         {
  708.           bkDict = new DBDictionary();
  709.           nod.UpgradeOpen();
  710.           bkdId = nod.SetAt(dictKey, bkDict);
  711.           tr.AddNewlyCreatedDBObject(bkDict, true);
  712.         }
  713.         // Get or create our background object
  714.         if (bkDict.Contains(bkKey))
  715.         {
  716.           sbId = bkDict.GetAt(bkKey);
  717.         }
  718.         else
  719.         {
  720.           SolidBackground sb = new SolidBackground();
  721.           sb.Color = ec;
  722.           sbId = bkDict.SetAt(bkKey, sb);
  723.           tr.AddNewlyCreatedDBObject(sb, true);
  724.         }
  725.         // And set it to the viewport
  726.         ViewportTableRecord vtr =
  727.           (ViewportTableRecord)tr.GetObject(
  728.             vtrId,
  729.             OpenMode.ForWrite
  730.           );
  731.         vtr.Background = sbId;
  732.       }
  733.     }
  734.     // Remove the previously set 3D background colour
  735.     private static void Remove3DBackground(
  736.       Database db,
  737.       Transaction tr,
  738.       ObjectId vtrId,
  739.       ObjectId sbId
  740.     )
  741.     {
  742.       // First remove it from the viewport
  743.       if (vtrId != ObjectId.Null)
  744.       {
  745.         ViewportTableRecord vtr =
  746.           (ViewportTableRecord)tr.GetObject(
  747.             vtrId,
  748.             OpenMode.ForWrite
  749.           );
  750.         vtr.Background = ObjectId.Null;
  751.       }
  752.       // And then erase the object itself (although
  753.       // I suspect this is redundant)
  754.       if (sbId != ObjectId.Null)
  755.       {
  756.         SolidBackground sb =
  757.           (SolidBackground)tr.GetObject(
  758.             sbId,
  759.             OpenMode.ForRead,
  760.             true
  761.           );
  762.         if (!sb.IsErased)
  763.         {
  764.           sb.UpgradeOpen();
  765.           sb.Erase();
  766.         }
  767.       }
  768.     }
  769.     // Return a grayscale version of a provided bitmap,
  770.     // with the option of forcing non-background pixels to
  771.     // be black
  772.     public static Bitmap ConvertToGrayscale(
  773.       Bitmap src,
  774.       System.Drawing.Color bgcol,
  775.       bool force,
  776.       System.Drawing.Color fgcol
  777.     )
  778.     {
  779.       // From http://www.bobpowell.net/grayscale.htm
  780.       Document doc =
  781.         Application.DocumentManager.MdiActiveDocument;
  782.       Editor ed = doc.Editor;
  783.       Bitmap bmp = new Bitmap(src.Width, src.Height);
  784.       for (int y = 0; y < bmp.Height; y++)
  785.       {
  786.         for (int x = 0; x < bmp.Width; x++)
  787.         {
  788.           System.Drawing.Color c = src.GetPixel(x, y);
  789.           int lum =
  790.             (force && !SameColors(c, bgcol) ?
  791.               0 :
  792.               (int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11)
  793.             // 0.299R + 0.587G + 0.114B
  794.             );
  795.           bmp.SetPixel(
  796.             x,
  797.             y,
  798.             (lum == 0 ?
  799.               fgcol :
  800.               System.Drawing.Color.FromArgb(lum, lum, lum))
  801.           );
  802.         }
  803.       }
  804.       return bmp;
  805.     }
  806.     // Return whether two colour can be considered equivalent
  807.     // in terms of RGB values
  808.     private static bool SameColors(
  809.       System.Drawing.Color a,
  810.       System.Drawing.Color b
  811.     )
  812.     {
  813.       // Ignore Alpha channel, just compare RGB
  814.       return (a.R == b.R && a.G == b.G && a.B == b.B);
  815.     }
  816.   }
  817. }
回复

使用道具 举报

发表回复

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

  • 微信公众平台

  • 扫描访问手机版

  • 点击图片下载手机App

QQ|关于我们|小黑屋|乐筑天下 繁体中文

GMT+8, 2025-6-28 22:50 , Processed in 3.211534 second(s), 59 queries .

© 2020-2025 乐筑天下

联系客服 关注微信 帮助中心 下载APP 返回顶部 返回列表