二.搭建一個Taskpane的SolidWorks插件

二.搭建一個Taskpane的SolidWorks插件

SolidWorks插件-將SolidWorks文件轉換為gltf格式

?雖然可以在另存為選項中擴展gltf功能摸柄,但為了在SolidWorks界面上顯而易見,我選擇了添加一個TaskPane界面既忆。


TaskPane.png

2.新建一個帶TaskPane的SolidWork插件

?使用SolidWors自帶SwCSharpAddin模板建立一個SolidWorks插件驱负,關于如何找到這個模板可以在看我的另一篇文章。

2.1 新建一個名未DuSwToglTF的插件
2.2 去掉和按鈕有關的代碼
2.3 添加一個名為Convert.xaml的WPF用戶控件.注意添加關于WPF的類庫引用

System.xaml;WindowsBase;WindowsFormsIntegration;PresentationCore;PresentionFramework;

  • 將UI Methods區(qū)域代碼刪除患雇,并添加AddTaskPanel()方法
        #region UI Methods
        private void AddTaskPanel()
        {
            try
            {
                //DuSwToglTF.ConvertPanel.PreloadDlls();
                ITaskpaneView pTaskPanView;
                pTaskPanView = iSwApp.CreateTaskpaneView2((ConvertPanel.RootPath+"\\"+ "gltf.bmp"), "將Solidworks文件轉換為glTF");
                if (TaskPanelControl == null)
                {
                    SwAddin.TaskPanelControl = new ConvertPanel(SwApp);
                    eleHost.Child = TaskPanelControl;
                }
                pTaskPanView.DisplayWindowFromHandlex64(eleHost.Handle.ToInt64());
            }
            catch (Exception ex)
            {
                SwApp.SendMsgToUser(ex.ToString());
            }
        }
        #endregion

這段代碼首先定義了一個TaskpaneView對象跃脊,然后通過ISldworks創(chuàng)建了一個TaskpaneView對象。緊接著實例化了一個WPF的用戶控件苛吱,
此處使用的一個ElementHost來作為WPF界面的容器酪术。此方面的介紹可以查看Winform與WPF的互操作性。最后調用DisplayWindowFromHandlex64方法顯示了這個WPF控件翠储,ToInt64()方法傳遞了一個指針給SolidWorks以便SolidWorks顯示绘雁。

2.4 在ConnectToSW方法中調用AddTaskPanel()
        public bool ConnectToSW(object ThisSW, int cookie)
        {
            iSwApp = (ISldWorks)ThisSW;
            addinID = cookie;

            //Setup callbacks
            iSwApp.SetAddinCallbackInfo(0, this, addinID);

            #region 添加Taskpane
            AddTaskPanel();
            #endregion

            #region Setup the Event Handlers
            SwEventPtr = (SolidWorks.Interop.sldworks.SldWorks)iSwApp;
            openDocs = new Hashtable();
            AttachEventHandlers();
            #endregion

            return true;
        }

3.使用WPF做一個轉換界面

接下來我們需要設計一下UI來實現我們的功能

3.1 安裝必要nuget庫
  • MVVMLight來實現MVVM模式
  • HandyControl 來美化UI

使用HandyControl注意在xaml文件中引用命名空間

             xmlns:hc="https://handyorg.github.io/handycontrol"

并添加資源字典

<UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml"/>
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
3.2 添加類 ConvertPanelViewModel.cs
namespace DuSwToglTF
{
    public class ConvertPanelViewModel:GalaSoft.MvvmLight.ViewModelBase
    {

    }
}
3.3 設計界面--完整的xaml文件如下
<UserControl x:Class="DuSwToglTF.ConvertPanel"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:DuSwToglTF"
             mc:Ignorable="d"              
            
             xmlns:hc="https://handyorg.github.io/handycontrol"
            TextElement.FontWeight="Medium"
            TextElement.FontSize="10"
            FontFamily="pack://application:,,,/MaterialDesignThemes.Wpf;component/Resources/Roboto/#Roboto"             
          d:DesignHeight="600" d:DesignWidth="300">
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml"/>
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
    <TabControl>
        <TabItem>
            <TabItem.Header>
                <Image Source="pack://application:,,,/DuSwToglTF;component/Resources/Main.png" Width="16" Height="16"></Image>
            </TabItem.Header>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="340"/>
                    <RowDefinition Height="16"/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Margin="0,0,-0.4,0">
                    <StackPanel Grid.Row="0" Margin="0" Grid.RowSpan="2">
                        <GroupBox Margin="0,10"  ToolTip="Save Path">
                            <GroupBox.Header >
                                <Label>保存路徑</Label>
                            </GroupBox.Header>
                            <Grid  Margin="0,10">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="43*"/>
                                    <RowDefinition Height="50"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="79*"/>
                                    <ColumnDefinition Width="21*"/>
                                </Grid.ColumnDefinitions>
                                <TextBox Text="{Binding FileName}"></TextBox>
                                <Label Grid.Row="0" Grid.Column="1" ToolTip="FileName">文件名</Label>
                                <TextBox Text="{Binding FilePath}" Grid.Column="0" Margin="2,10"  Grid.Row="1"/>
                                <Button Grid.Column="1" Command="{Binding ChoosePathCommand}" Content="..." Margin="0,10" Height="30" ToolTip="選擇保存路徑" Grid.Row="1"/>
                            </Grid>
                        </GroupBox>
                        <Button Margin="10,2" Command="{Binding SaveCommand}"   Click="Button_Click">
                           保存(Save)
                        </Button>
                        <!--<StackPanel Orientation="Horizontal">
                            <ProgressBar HorizontalAlignment="Stretch" Width="295"></ProgressBar>
                        </StackPanel>-->
                        <Grid  Margin="2">
                            <hc:Card Header="選項">
                                <StackPanel>
                                    <StackPanel Margin="0,5" Orientation="Horizontal">

                                        <CheckBox HorizontalAlignment="Left" Margin="10,0"  IsChecked="{Binding IsOpenFile}"
                                  ToolTip="保存完成后打開文件(Open gltf file after saved)">
                                        保存完打開
                                        </CheckBox>
                                        <CheckBox HorizontalAlignment="Left" Margin="10,0"  IsChecked="{Binding IsOpenFolder}"
                                  ToolTip="保存完成后打開文件夾(Open folder after saved)">
                                            保存完成后打開文件夾
                                        </CheckBox>
                                    </StackPanel>
                                    <Slider Margin="0,10" VerticalAlignment="Center"
  Minimum="0"
  Maximum="100"
  
  ToolTip="網格精度(待實現)"
  Value="50"
  />
                                </StackPanel>
                            </hc:Card>
                        </Grid>
                        <GroupBox Header="批量轉換" Visibility="Collapsed">
                        </GroupBox>
                    </StackPanel>
                </ScrollViewer>
                <GridSplitter Grid.Row="1" Background="AliceBlue" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Stretch" Margin="0,7,-0.4,7"  />
                <Grid Grid.Row="2" Margin="0,0,-0.4,0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="14*"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <!--<materialDesign:Card>
                        <GroupBox Header="批量轉換(開發(fā)中)" Margin="5,10">
                            <StackPanel>

                            </StackPanel>
                        </GroupBox>
                    </materialDesign:Card>-->
                </Grid>
            </Grid>
        </TabItem>
        <TabItem>
            <TabItem.Header>
                <Image Source="pack://application:,,,/DuSwToglTF;component/Resources/About.png" Width="16" Height="16"></Image>
            </TabItem.Header>
            <StackPanel>
                <Grid Margin="5">
                    <GroupBox >
                        <GroupBox.Header>
                            <Label ToolTip="Info">信息</Label>
                        </GroupBox.Header>
                        <StackPanel>
                            <TextBlock HorizontalAlignment="Center" FontSize="15" Margin="5">
                    DuSwToglTF V0.0.1 Preview
                            </TextBlock>
                            <TextBlock Margin="4">1.支持格式:sldprt,sldasm轉換為glTF文件</TextBlock>
                            <TextBlock Margin="4" TextWrapping="Wrap">2.對多實體零件或者裝配體的輸出未進行測試,可能產生錯誤</TextBlock>
                            <TextBlock Margin="4">2.包含幾何信息和顏色信息,單一面的顏色信息暫未考慮</TextBlock>
                            <TextBlock Margin="4">3.暫未支持光照度,場景橡疼,動畫等功能</TextBlock>
                        </StackPanel>
                    </GroupBox>
                </Grid>


                <Grid Margin="5" >
                    <Expander Header="NuGet">
                        <!--<Expander.Header >
                            <Label  ToolTip="使用的庫或框架">使用的庫或框架
                            </Label>
                        </Expander.Header>-->
                        <StackPanel>
                            <Label>1.HandyControl</Label>
                            <Label>2.MVVM-MVVMLight</Label>
                            <Label>2.glTF-sharpglTF</Label>
                        </StackPanel>
                    </Expander>
                </Grid>
                <Grid Margin="5" >
                    <GroupBox Header="項目信息">
                        <StackPanel>
                            <TextBlock>
                                <Hyperlink></Hyperlink>
                            </TextBlock>
                            <TextBlock Margin="5">Code by DuDuDu</TextBlock>
                            <TextBlock Margin="5">Contact me:1831197727@qq.com</TextBlock>
                            <StackPanel Orientation="Horizontal">
                                <Label>Project:</Label>
                                <TextBlock VerticalAlignment="Center">
                                <Hyperlink>https://github.com/weianweigan/DuSwToglTF</Hyperlink>
                                </TextBlock>
                            </StackPanel>
                        </StackPanel>
                    </GroupBox>
                </Grid>
            </StackPanel>
        </TabItem>
    </TabControl>
</UserControl>
3.4將相應屬性綁定到viewmodel上

詳細的代碼可以去GitHub查看

3.5 關于實時獲取當前打開的文檔,以便自動填寫文件路徑和名字咧七。

為了在打開零件或者裝配體時自動填寫文件名和當前打開的文件路徑衰齐,我們需要監(jiān)聽切換文檔的事件任斋。

  • 在SwAddin.cs類的OnDocChange()方法中設置文檔名字和路徑
 public int OnDocChange()
        {
            TaskPanelControl.viewmodel.SetModelDoc();
            return 0;
        }
3.6 實現ConvertPanelViewModel中的SaveClick()方法
  /// <summary>
        /// 保存按鈕執(zhí)行的動作
        /// </summary>
        private  void  SaveClick()
        {
            List<string> files = null;
            Controller.Convertor.ErrorType errors = Controller.Convertor.ErrorType.NoErros;
            IsInProgress = true;

            if (!System.IO.Directory.Exists(FilePath))
            {
                swApp.SendMsgToUser("當前路徑不存在:" + FilePath);
                return;
            }
            if (FilePath.Contains("-") || FileName.Contains("-"))
            {
                swApp.SendMsgToUser("-為非法字符继阻,路徑或者文件民包含-字符,請修改路徑或者文件名后重新保存");
                return;
            }
            try
            {
                //會堵塞UI废酷;TODO:異步方式實現轉換
                var model =  Controller.Convertor.DuConvertor.ConvertToglTFModel(swModel, out errors);
                if (model != null)
                {
                    files =  Controller.Convertor.DuConvertor.SaveAs(model, FilePath, FileName);
                }
                swApp.SendMsgToUser("保存完成");
                if (files != null && IsOpenFile && files.Count >= 3)
                {
                    System.Diagnostics.Process.Start( files[2]);
                }
                if (IsOpenFolder)
                {
                    System.Diagnostics.Process.Start("explorer.exe", FilePath);
                }
                IsInProgress = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
           
            // System.Diagnostics.Process.Start("ExpLore", "C:\\window");
        }

*下面將介紹對SolidWorks模型處理和保存瘟檩。

 var model =  Controller.Convertor.DuConvertor.ConvertToglTFModel(swModel, out errors);
                if (model != null)
                {
                    files =  Controller.Convertor.DuConvertor.SaveAs(model, FilePath, FileName);
                }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市澈蟆,隨后出現的幾起案子墨辛,更是在濱河造成了極大的恐慌,老刑警劉巖趴俘,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件睹簇,死亡現場離奇詭異,居然都是意外死亡寥闪,警方通過查閱死者的電腦和手機太惠,發(fā)現死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來疲憋,“玉大人凿渊,你說我怎么就攤上這事「苛” “怎么了埃脏?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長秋忙。 經常有香客問我彩掐,道長,這世上最難降的妖魔是什么灰追? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任佩谷,我火速辦了婚禮,結果婚禮上监嗜,老公的妹妹穿的比我還像新娘谐檀。我一直安慰自己,他們只是感情好裁奇,可當我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布桐猬。 她就那樣靜靜地躺著,像睡著了一般刽肠。 火紅的嫁衣襯著肌膚如雪溃肪。 梳的紋絲不亂的頭發(fā)上免胃,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天,我揣著相機與錄音惫撰,去河邊找鬼羔沙。 笑死,一個胖子當著我的面吹牛厨钻,可吹牛的內容都是我干的扼雏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼夯膀,長吁一口氣:“原來是場噩夢啊……” “哼诗充!你這毒婦竟也來了?” 一聲冷哼從身側響起诱建,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤蝴蜓,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后俺猿,有當地人在樹林里發(fā)現了一具尸體茎匠,經...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年押袍,在試婚紗的時候發(fā)現自己被綠了诵冒。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡伯病,死狀恐怖造烁,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情午笛,我是刑警寧澤惭蟋,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站药磺,受9級特大地震影響告组,放射性物質發(fā)生泄漏。R本人自食惡果不足惜癌佩,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一木缝、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧围辙,春花似錦我碟、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春厘托,著一層夾襖步出監(jiān)牢的瞬間友雳,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工铅匹, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留押赊,地道東北人。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓包斑,卻偏偏與公主長得像流礁,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子舰始,可洞房花燭夜當晚...
    茶點故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內容

  • 目錄 什么是WPF崇棠? WPF的歷史咽袜? 為什么要用WPF及WPF作用 WPF與winForm區(qū)別丸卷? 什么是WPF? ...
    灬52赫茲灬閱讀 5,812評論 2 11
  • 2.1 新建WPF項目 ### 略 2.2 剖析最簡單的XAML代碼 XAML是XML派生的 為了表示同類標簽中的...
    北風知我意閱讀 3,208評論 0 0
  • 一询刹、WPF簡介 WPF:WPF即Windows Presentation Foundation谜嫉,翻譯為中文“Win...
    UnicornChen閱讀 13,704評論 0 3
  • 今天可謂是輕松的一天,學生已經放假凹联,剩下瑣碎的任務也完成了七七八八沐兰,我決定今天什么都不做,讓自己過一個輕松愉...
    蝸居女士閱讀 274評論 0 2
  • 老農為啥一夜之間瓜田盡失蔽挠?他該如何東山再起住闯?又是如何成為歷下首富也?且聽本回貓說江湖事外傳之老農賣瓜 老農淚下澳淑,坐...
    自來詩閱讀 1,299評論 19 34