Editing Solidwork's system options in C# - c#

I am trying to edit a couple of settings in SolidWork's options menu through a C# program I wrote. The code is below:
using System;
using System.IO;
using SldWorks;
using SwConst;
static void Main(string[] args)
{
SldWorks.SldWorks swApp;
swApp = new SldWorks.SldWorks();
swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swSingleCommandPerPick, true); /// Single command per pick
swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swEditMacroAfterRecord, true); /// Automatically edit macro after recording
swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swUserEnableFreezeBar, true); /// Enable Freeze bar
Console.WriteLine("Settings applied");
}
The intended purpose of this program is to toggle those three options (checkboxes) to true. So far this does not work at all. The options still stay the same even after I run the program. Am I missing anything or is my code wrong?

Try this (for example, mouse speed):
//View rotation - Mouse speed
bool boolstatus = swApp.SetUserPreferenceIntegerValue((int)swUserPreferenceIntegerValue_e.swViewRotationMouseSpeed, 56);
Thanks to Solidworks API:
http://help.solidworks.com/2012/English/api/sldworksapi/Get_and_Set_User_Preferences_Example_CSharp.htm

Try using the following to get the COM object while SolidWorks is running.
Try
{
SldWorks swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swSingleCommandPerPick, true); /// Single command per pick
swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swEditMacroAfterRecord, true); /// Automatically edit macro after recording
swApp.SetUserPreferenceToggle((int)swUserPreferenceToggle_e.swUserEnableFreezeBar, true); /// Enable Freeze bar
Console.WriteLine("Settings applied");
}
catch()
{
Console.WriteLine("Failed to get SolidWorks");
}

Related

Enable/Disable Spatial Mapping at runtime in MRTK2

With the new MRTK2 I'm looking to disable spatial mapping after we are done using it to place GameObjects. I'm stuck on what exactly to call in the namespace or on the service to do this at run time.
I've tried: MixedRealityToolkit.SpatialAwarenessSystem.SuspendObservers();
This has no effect. I could disable the entire "Spatial Awareness System" GameObject, but this would be a hack.
What I need is the proper call that would disable the system entirely so that resources are freed up when it is no longer useful?
Additionally, a little insight into how we are to access the service system correctly would be of great help.
You can use the following code to disable/enable the spatial awareness system:
if (disable)
{
// disable
MixedRealityToolkit.SpatialAwarenessSystem.Disable();
}
else
{
// enable
MixedRealityToolkit.SpatialAwarenessSystem.Enable()
}
You can use the following code to enable/disable just the visualization but keep the colliders on:
foreach(var observer in MixedRealityToolkit.SpatialAwarenessSystem.GetObservers())
{
var meshObserver = observer as IMixedRealitySpatialAwarenessMeshObserver;
if (meshObserver != null)
{
meshObserver.DisplayOption = SpatialAwarenessMeshDisplayOptions.None;
}
}
You can read more documentation about the Spatial Awareness system in MRTK on the mrtk github.io site at Spatial Awareness System Usage guide
I would have expected the SuspendObservers() method to result in no new meshes being displayed. Do you see the meshes changing after suspending?
It is by design for the meshes to remain visible until the application explicitly sets their visibility to None via the IMixedRealitySpatialAwarenessMeshObserver.DisplayOption property.
Thanks!
Note the previous answer doesn't work due to recent changes to the MRTK framework.
Link for SpatialAwareness DataProvidershere
Code pasted from said link:
IMixedRealityDataProviderAccess dataProviderAccess =
CoreServices.SpatialAwarenessSystem as IMixedRealityDataProviderAccess;
if (dataProviderAccess != null)
{
IReadOnlyList<IMixedRealitySpatialAwarenessMeshObserver> observers =
dataProviderAccess.GetDataProviders<IMixedRealitySpatialAwarenessMeshObserver>();
foreach (IMixedRealitySpatialAwarenessMeshObserver observer in observers)
{
// Set the mesh to use the occlusion material
observer.DisplayOption = SpatialMeshDisplayOptions.Occlusion;
}
}
[AddComponentMenu("Scripts/MRTK/Examples/ClearSpatialObservations")]
public class ClearSpatialObservations : MonoBehaviour
{
/// <summary>
/// Indicates whether observations are to be cleared (true) or if the observer is to be resumed (false).
/// </summary>
private bool clearObservations = true;
/// <summary>
/// Toggles the state of the observers.
/// </summary>
public void ToggleObservers()
{
var spatialAwarenessSystem = CoreServices.SpatialAwarenessSystem;
if (spatialAwarenessSystem != null)
{
if (clearObservations)
{
spatialAwarenessSystem.SuspendObservers();
spatialAwarenessSystem.ClearObservations();
clearObservations = false;
}
else
{
spatialAwarenessSystem.ResumeObservers();
clearObservations = true;
}
}
}
}

XNA and Windows Forms

I am trying to make a main menu in Windows Forms. When you click a label in the form, the XNA game should start playing.
But it didn't work.
my code in the program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace _2DSpaceShooter
{
if WINDOWS || XBOX
static class Program
{
static void Main(string[] args)
{
Application.Run(new MainMenu());
}
}
endif
}
My code in the label click event
private void label1_Click(object sender, EventArgs e)
{
using (Game1 game = new Game1())
{
game.Run();
}
}
Please help me!!!
I am sorry for possible English mistakes (I am not American)
I don't know if you can do it, but if you can one of the simplest way is by using GameComponents. Making your game as a GC enables you to launch multiples parts of it at one time, without having issues with threads.
As #eudabash mentioned in the comment section, you'll need to do the game.Run() in a seperate thread:
Game1 game = new Game1();
Thread thread = new Thread(() =>
{
game.Run();
};
thread.Start();
or, if you're on .Net 4.0 (I think. Or even 3.5)
Game1 game = new Game1();
Task.Factory.StartNew(() =>
{
game.Run();
}
Optionally make 'game' a field in your Form1 class, so you can access it anywhere. Just make sure to only retrieve data from Game, and never edit the UI from within Game. Cross-thread operations and whatnot. If you need to, remember to invoke.

ActiveX VLC plugin for WPF wont mute

I'm using a simple open file dialogue to open a video file and play it via VLC. All works great, but I can NOT get the volume to mute for the life of me.
System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.ShowDialog();
if (ofd.FileName != "")
{
vlc.addTarget("file:///" + ofd.FileName, null,AXVLC.VLCPlaylistMode.VLCPlayListReplaceAndGo, 0);
vlc.play();
vlc.AutoLoop = true;
vlc.Volume = 0;
vlc.toggleMute();
}
I have tried setting volume to 0 and there toggleMute function with no luck. I have also tried doing the mute functionality in the playEvent, with no luck. Could anyone shine some light on the situation?
EDIT: So, I tossed in a System.Threading.Thread.Sleep(1000); before my call to adjust the volume and mute. To my surprise, the volume is muted after a one second delay. Does anyone have a "real" fix for this as it seems like it could cause issues / not work correctly on slower machines
This issue occurse since VLC 2.0.9.
VLC version 2.0.8 doenst need an delay.
All versions >2.0.8 need delays...
Solution is use version 2.0.8 and it works fine.
/// <summary>
/// Play a filename
/// </summary>
/// <param name="fileName">filename</param>
public void Play(string fileName)
{
this.VlcControl.Media = new Vlc.DotNet.Core.Medias.PathMedia(fileName);
Task.Factory.StartNew(this.Mute);
}
/// <summary>
/// Mute audio
/// </summary>
private void Mute()
{
this.VlcControl.AudioProperties.IsMute = true;
if (!this.VlcControl.AudioProperties.IsMute)
{
// Retry mute
Task.Factory.StartNew(this.Mute);
}
}

Making simple console menu in c#

I want to make a simple menu in C# like :
something like this should be printed out of console :
FirstOption
SecondOption
Exit
So far here is my code (there are problems with naming and encapsulation, but this is all just quick prototype, spent ~30 minutes):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Menu StartGame = new Menu("Start Game");
Menu EndGame = new Menu("End Game");
Console.WriteLine(StartGame);
Console.WriteLine(End Game);
EndGame.isChecked = false;
}
}
class Menu
{
private string Content;
public bool isChecked = true;
public Menu(string Content)
{
this.Content = Content;
}
public void CheckCondition()
{
if (isChecked)
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
}
else
{
Console.ResetColor();
}
}
public override string ToString()
{
this.CheckCondition();
return this.Content;
}
}
}
The idea is when a button is clicked the menu item is highlighted. When one come to the last menu item he can't press DownArrow again, the same for the first item and UpArrow.
I'm completely stuck with this.
I am not completely sure.. May be this could help you to get started.
while (true)
{
var ch = Console.ReadKey(false).Key;
switch (ch)
{
case ConsoleKey.UpArrow:
HighlightStartGame();
break;
case ConsoleKey.DownArrow:
HighlightEndGame();
break;
}
}
static void HighlightStartGame()
{
Console.Clear();
Console.ResetColor();
StartGame.isChecked = true;
Console.WriteLine(StartGame);
EndGame.isChecked = false;
Console.WriteLine(EndGame);
}
static void HighlightEndGame()
{
Console.Clear();
Console.ResetColor();
StartGame.isChecked = false;
Console.WriteLine(StartGame);
EndGame.isChecked = true;
Console.WriteLine(EndGame);
}
No you can't just do that because Win32 console doesn't support those methods. You can however use GDI to draw on the console window.
The problem is that the console cannot process any mouse events. How do you want to click on the menu? You will have to do everything with keys. The options you have are to either define keystrokes (like Ctrl-F or Alt-F for "FirstEntry") in order to activate menu entries, or to implement a navigation with arrow keys, allowing you to move around fields (button or menu fields and text fields). This is not built in, so you will have to do everything in code. You will have to use the SetCursorPosition and the ReadKey methods of the console in order to achieve this. I remember having done this on a VT100 terminal eons ago.
I've written a console menu library for C#. It has no mouse support, but it might still be a starting point for you?
CMenu is a lightweight, low-ceremony framework for building console
menus in .Net. Instead of manually prompting the user for input and
parsing it, you define commands in a short, structured and
comprehensive way, and let CMenu handle the rest.
CMenu aims for low overhead - simple stuff should be simple to
implement. If you don't use a feature, you don't need to know anything
about it.
At the same time, complex scenarios are supported. Large menus can
easily be split into several classes. Background self-configuration.
You do not have to worry about all the annoying details involved in
larger menus, it will just work.
Most importantly, it is very simple and fast to use. Commands can be
abbreviated, a smart parser enables even partial matching. A help
command is integrated.

nullReferenceException when i try to play a sound effect?

I'm making a soundboard with sound effects and I'm getting :
"A first chance exception of type 'System.NullReferenceException'"
when building after 'UI Task' (Managed):
Loaded 'Microsoft.Xna.Framework.dll'
I did have it working but after changes (overwrote previous version) I have been getting this error and I'm stuck. Java is my first language and with C# I'm a beginner. I have spent countless hours looking for a solution.
The nullReferenceException is coming from loadsound(), I think! I have the sound files(.wav) in a folder called resources and build action:resources and copy to output:do not copy(have tried all options here). Also in references a reference was made to Microsoft.Xna.Framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Resources;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
namespace Craggy_Island
{
public partial class MainPage : PhoneApplicationPage
{
// The Resources to play
private SoundEffect drink;//(plus 23 more effects)
// Flag that indicates if we need to resume Zune playback upon exiting.
bool resumeMediaPlayerAfterDone = false;
// Constructor
public MainPage()
{
InitializeComponent();
// Timer to simulate the XNA game loop (SoundEffect class is from the XNA Framework)
GameTimer gameTimer = new GameTimer();
gameTimer.UpdateInterval = TimeSpan.FromMilliseconds(33);
// Call FrameworkDispatcher.Update to update the XNA Framework internals.
gameTimer.Update += delegate { try { FrameworkDispatcher.Update(); } catch { } };
// Start the GameTimer running.
gameTimer.Start();
// Prime the pump or we'll get an exception.
FrameworkDispatcher.Update();
//LoadSound("Resources/drink.wav", out drink);
// Create and load SoundEffect objects.
LoadSound("Resources/drink.wav", out drink);
}
private void LoadSound(String SoundFilePath, out SoundEffect Sound)
{
// For error checking, assume we'll fail to load the file.
Sound = null;
try
{
// Holds informations about a file stream.
StreamResourceInfo SoundFileInfo = App.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));
// Create the SoundEffect from the Stream
Sound = SoundEffect.FromStream(SoundFileInfo.Stream);
}
catch (NullReferenceException)
{
// Display an error message
MessageBox.Show("Couldn't load sound " + SoundFilePath);
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
Button Current = sender as Button;
try
{
if (Current.Equals(button1))
drink.Play();//(other buttons here for other sound effects)
}
catch (NullReferenceException)
{
MessageBox.Show("Can't play, sound file problem.");
}
}
#region Zune Pause/Resume
private void ZunePause()
{
// Please see the MainPage() constructor above where the GameTimer object is created.
// This enables the use of the XNA framework MediaPlayer class by pumping the XNA FrameworkDispatcher.
// Pause the Zune player if it is already playing music.
if (!MediaPlayer.GameHasControl)
{
MediaPlayer.Pause();
resumeMediaPlayerAfterDone = true;
}
}
private void ZuneResume()
{
// If Zune was playing music, resume playback
if (resumeMediaPlayerAfterDone)
{
MediaPlayer.Resume();
}
}
#endregion Zune Pause/Resume
}
}
Scrap my original answer unless you're using XNA for game development on Windows/Xbox. (Original poster is using it for the Zune.)
Regarding the WAV file:
First problem is that you need to set Copy to Output Directory to Copy if newer. (You could use Always, but that would be unnecessary.)
Second problem is that its type needs to be set to Content.
You are taking the hard approach. Look into ContentManager (accessible as this.Content from within the Game instance). You can use Content.Load<T>(string) to access your audio file, but you'll need to put the audio file in the content project. Don't change its type: leave it at the default. Even it's not a resource, leave it be. It will be compiled into a different format. Also, omit the file extension from the parameter passed to Content.Load<>.
You are starting the game before you are loading the sound:
gameTimer.Start();
FrameworkDispatcher.Update();
LoadSound("Resources/drink.wav", out drink);
I had almost the same problem. Finally I got it accidently as follows:
StreamResourceInfo streaminfo = Application.GetResourceStream(new Uri("project_name;component/folder_name/Sound3.wav", UriKind.RelativeOrAbsolute));
SoundEffect effect1 = SoundEffect.FromStream(streaminfo.Stream);
effect1.Play();
AND:
the Property "Build Action" of the .wav file must be setted to "Resource" and the Porperty "Copy to Output Directory" should be setted to "Copy if newer"
By the way, I´m working with Silverlight5.

Categories

Resources