How to use Shell32 within a C# application? - c#

What should I include within a C# application in order to make Shell32 work?
Edit:
My application can't recognize shell32. What references or lib should I include? What I'm trying to do is:
Shell32.Shell shell = new Shell32.Shell();
What I'm getting as an error:
Error 1 The type or namespace name 'Shell32' could not be found (are you missing a using directive or an assembly reference?)

Just add a reference to Shell32.dll from the Windows\System32 folder and use it:
Shell32.Shell shell = new Shell32.Shell();
shell.MinimizeAll();

maybe this can help:
Right click project
Click Add reference
Click .COM tab in Add reference dialogue
Select Microsoft Shell Controls and Automation
Click OK
your shell32 is ready to use...

I know this thread is old, but I post this for anyone having the same problem as I did. The solution above does not compile under windows 8
Shell32.Shell shell = new Shell32.Shell(); <= this doesn't work with windows 8
Use the work around below if you want your apps to run under windows 8.
using Shell32;
private Shell32.Folder GetShell32Folder(string folderPath)
{
Type shellAppType = Type.GetTypeFromProgID("Shell.Application");
Object shell = Activator.CreateInstance(shellAppType);
return (Shell32.Folder)shellAppType.InvokeMember("NameSpace",
System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { folderPath });
}

Right click your project in the solution explorer.
Choose "Add Reference..." from the drop-down menu.
Click the "Browse" tab.
Navigate to the C:\Windows\System32 directory.
Choose the shell32.dll file. and press the "OK" button.
You now have the appropriate reference for using Shell32.Shell.

Add to your project a reference to the COM library Microsoft Shell Controls and Automation. Additionally, ensure that the code using Shell32.Shell is running in a single threaded apartment, e.g. by adding the [STAThread] attribute to Main.

I'm guessing that you're having trouble getting any calls recognized, so I'd refer you to this general article: http://www.codeproject.com/KB/shell/csdoesshell1.aspx
Beyond that, you'll need to provide specifics of what isn't working for you.

The class shown below should help with some of the methods of shell32 in C# .
you should add the reference of "Microsoft Shell command and automation" with the reference window by righting clicking the project .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MusicMuttPrototype
{
public class clsShellFileInfo
{
public Exception errorException;
public enum FileDetailInfo
{
Name = 0,
Year = 15,
Size = 1,
Track_Number = 19,
Type = 2,
Genre = 20,
Date_Modified = 3,
Duration = 27,
Date_Created = 4,
Bit_Rate = 28,
Date_Accessed = 5,
Protected = 23,
Attributes = 6,
Camera_Model = 24,
Status = 7,
Date_Picture_Taken = 25,
Owner = 8,
Dimensions = 26,
Author = 9,
Not_used = 27,
Title = 10,
Not_used_file = 28,
Subject = 11,
//Not_used = 29,
Category = 12,
Company = 30,
Pages = 13,
Description = 31,
Comments = 14,
File_Version = 32,
Copyright = 15,
Product_Name_Chapter = 33,
//Scripting Quicktest Profess11ional Page 63
Artist = 16,
Product_Version = 34,
Album_Title = 17,
Retrieves_the_info_tip_inf = -1
}
public string getFileDetails(string fileFolder, string filePath, FileDetailInfo infotype)
{
string strReturnval = "";
try
{
Shell32.Shell fileshell = new Shell32.Shell();
Shell32.Folder fileshellfolder = fileshell.NameSpace(fileFolder);
Shell32.FolderItem Item = fileshellfolder.ParseName(filePath);
strReturnval = fileshellfolder.GetDetailsOf(Item, (int)infotype);
}
catch (Exception ex)
{
errorException = ex;
}
return strReturnval;
}
}
}

If you don't need the full set of API calls, you maybe better off creating a COM import stub class. See how Mike Ward who wrote Desk Drive did it.
Link 1
Link 2

C# .Net
I do not understand the full question but this is working for me.
[DllImport("Shell32.dll")]
public static extern int ShellExecuteA(int hwnd, string lpOperation, string lpFile, int lpParameters, int lpDirecotry, int nShowCmd);
private void pictureBox1_Click(object sender, EventArgs e)
{
int open;
open = ShellExecuteA(0, "open", "https://google.com", 0, 0, 1);
}
Using a picturebox to open a link.

Related

Newbie Lucene Problem with c# demo "The Type or Namespace 'StandardAnalyzer' could not be found"

I'm trying to get the basic demo of Lucene.net (4.8.0-beta00012) to run.
http://lucenenet.apache.org/#quick-start
I've created a new Forms App.
Run Install-Package Lucene.Net -Pre and it's downloaded the nuget package.
Copied and pasted all the demo sections: Create an index and define a text analyzer, Add to the index, Construct a query, and Fetch the results.
Visual Studio popped up a load of missing assembly references so I clicked 'Potential Fixes' and let it add the using statements at the start.
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Util;
using System;
using System.Windows.Forms;
namespace Lucene_CS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Ensures index backwards compatibility
var AppLuceneVersion = LuceneVersion.LUCENE_48;
var indexLocation = #"C:\Index";
var dir = FSDirectory.Open(indexLocation);
//create an analyzer to process the text
var analyzer = new StandardAnalyzer(AppLuceneVersion);
//create an index writer
var indexConfig = new IndexWriterConfig(AppLuceneVersion, analyzer);
var writer = new IndexWriter(dir, indexConfig);
var source = new
{
Name = "Kermit the Frog",
FavoritePhrase = "The quick brown fox jumps over the lazy dog"
};
Document doc = new Document
{
new StringField("name",
source.Name,
Field.Store.YES),
new TextField("favoritePhrase",
source.FavoritePhrase,
Field.Store.YES)
};
writer.AddDocument(doc);
writer.Flush(triggerMerge: false, applyAllDeletes: false);
// search with a phrase
var phrase = new MultiPhraseQuery
{
new Term("favoritePhrase", "brown"),
new Term("favoritePhrase", "fox")
};
// re-use the writer to get real-time updates
var searcher = new IndexSearcher(writer.GetReader(applyAllDeletes: true));
var hits = searcher.Search(phrase, 20 /* top 20 */).ScoreDocs;
foreach (var hit in hits)
{
var foundDoc = searcher.Doc(hit.Doc);
hit.Score.Dump("Score");
foundDoc.Get("name").Dump("Name");
foundDoc.Get("favoritePhrase").Dump("Favorite Phrase");
}
}
}
}
Now I am left with a couple that won't resolve:
var analyzer = new StandardAnalyzer(AppLuceneVersion);
And .Dump
hit.Score.Dump("Score");
foundDoc.Get("name").Dump("Name");
foundDoc.Get("favoritePhrase").Dump("Favorite Phrase");
How would I go about debugging this to determine how to specify the references correctly?
UPDATE WITH namespace Lucene.Net.Analysis.Standard
StandardAnalyzer is located in namespace Lucene.Net.Analysis.Standard.
I don't have an answer for you with regard to .Dump exactly.
hit.Score is a float, so hit.Score.Dump("Score"); is a bit hard for me to imagine. I did a search of the lucene net repository for the word Dump and there are only 20 occurrences. https://github.com/apache/lucenenet/search?p=1&q=Dump
One of them is the code tutorial example you are citing. But none of the other occurrences appear to be the implementation of that Dump method. So I'm gonna guess that the .Dump is no longer a valid method for the uses cited.
I'd recommend changing
foreach (var hit in hits)
{
var foundDoc = searcher.Doc(hit.Doc);
hit.Score.Dump("Score");
foundDoc.Get("name").Dump("Name");
foundDoc.Get("favoritePhrase").Dump("Favorite Phrase");
}
to
foreach (var hit in hits)
{
var foundDoc = searcher.Doc(hit.Doc);
var score = hit.Score;
var name = foundDoc.Get("name");
var favoritePhrase = foundDoc.Get("favoritePhrase");
}
That will probably work for you and allow you to inspect the fields retrieved via the debugger.
I might add that while the info on Lucene.Net can seem a bit limiting for a beginner, the system is amazing and crazy powerful. I say that to encourage you as you are learning it because it's well worth learning. I love it.
Update
Just as #bendecko said in the comment below, you need to install the package Lucene.Net.Analysis.Common from NuGet. Sorry I didn't specify that when providing the namespace.

Write Picture to mp3 File ID3.NET Windows Store Apps

I'm working in my new app to modify the ID3 Tags.
I can edit title,album and artists but I can't modify the Pictures.
Here is my small code
IList<string> artists = new List<string> { "test artist" };
tag.Title.Value = "my test";
tag.Album.Value = "album test";
tag.Artists.Value.Add("test artist");
tag.Pictures.Add(new Id3.Frames.PictureFrame
{
PictureData = array,
PictureType = Id3.Frames.PictureType.Media,
MimeType = "image/jpeg"
});
stream.WriteTag(tag, 1, 0, WriteConflictAction.Replace);
stream.Dispose();
When I open the mp3 file I can't see the image while it's playing.
Could you help me? Thank you.
stream.WriteTag(tag, 1, 0, WriteConflictAction.Replace);
1 represents the major and 0 the minor ID3 version. Since media types such as pictures/images are not implemented in version 1, you'll need to use at least version 2. (2.3 being the most popular version used in ID3 tagging libraries and 2.4 being the newest version released in 2000)
stream.WriteTag(tag, 2, 3, WriteConflictAction.Replace);
will resolve your issue. Please note that you also need to create an Idv23Tag when applying the code above:
var tag = new Id3v23Tag();
See http://en.wikipedia.org/wiki/ID3 for more information.

Using Hidden Security Icons in Taskdialog

I am trying to display a Security Success Icon (with the blue background) in TaskDialog message box. This is not one of the enum values of TaskDialogStandardIcon. Reference: http://dotnet.dzone.com/articles/using-new-taskdialog-winapi.
How do I assign these non standard values to ((TaskDialog)sender).Icon ? Is it even possible in C#? C#
Any pointers would be really helpful.
Regards,
Ashwin
I think you will need to import TaskDialog function from comctl32.dll yourself:
static class TaskDialogWrapper
{
[DllImport("comctl32.dll", CharSet = CharSet.Unicode, EntryPoint = "TaskDialog")]
static extern int TaskDialog(IntPtr hWnd, IntPtr hInstance, string pszWindowTitle, string pszMainInstruction, string pszContent, TaskDialogCommonButton dwCommonButtons, IntPtr pszIcon, out IntPtr pnButton);
public static TaskDialogCommonButton Show(IntPtr handle, IntPtr instance, string title, string instructionText, string content, TaskDialogCommonButton commonButtons, TaskDialogCommonIcon commonIcon)
{
IntPtr resultButton;
if (TaskDialog(handle, instance, title, instructionText, content, commonButtons, new IntPtr((int)commonIcon), out resultButton) != 0)
throw new InvalidOperationException();
return (TaskDialogCommonButton)resultButton;
}
}
[Flags()]
enum TaskDialogCommonButton
{
Ok = 0x1,
Yes = 0x2,
No = 0x4,
Cancel = 0x8,
Retry = 0x10,
Close = 0x20
}
enum TaskDialogCommonIcon
{
ShieldGrey = 65527,
ShieldOk = 65528,
ShieldError = 65529,
ShieldWarning = 65530,
ShieldBlue = 65531,
Shield = 65532,
Information = 65533,
Error = 65534,
Warning = 65535,
}
To use your own icon from a file, you will need to import TaskDialogIndirect.
(Btw., I found many other interesting icon styles for TaskDialogCommonIcon. You could add e.g.:
enum TaskDialogCommonIcon
{
None = 0,
Sheet = 2,
ExplorerFolderOpen = 3,
ExplorerFolderFlat = 5,
ExplorerFolderLeft = 6,
Search = 8,
ExplorerFolderClosed = 10,
ExplorerGames = 14,
Application = 15,
TransparentSpace = 17,
ExplorerSearch = 18,
TextFile = 19,
Letter = 20,
Picture = 21,
Diashow = 103,
// ...
}
I know that this is an old question, but I was looking for something similar, so I thought I'd pass along what I've found. Using the information posted by #KnorxThieus, I found a way to use the "hidden" security icons in the TaskDialog without going through the DLLImport process outlined above. Using the actual values he provided for the TaskDialogCommonIcon enumeration, I found that you can simply cast them to the appropriate type (i.e., the TaskDialogCommonIcon), and your application should display them properly.
Please note, I'm using the WindowsAPICodePack version 1.1.2 from Nuget (nuget.org/packages/WindowsAPICodePack-Core), and the code below has been converted from Visual Basic using the Telerik Code Converter (http://converter.telerik.com/), so it's possible that you may have to do some fine-tuning in C#:
if (TaskDialog.IsPlatformSupported) {
using (TaskDialog dialog = new TaskDialog()) {
dialog.Caption = "TESTING";
dialog.InstructionText = "THIS IS A TEST";
dialog.Text = "This is a test of casting a value to the desired Icon type for a TaskDialog.";
// Produces the green shield with green background
dialog.Icon = (TaskDialogStandardIcon)65528;
dialog.OwnerWindowHandle = this.Handle;
dialog.Show();
}
}
In my testing, this seems to work for all of the enumerations #KnorxThieus listed, as well as several others. I'm trying to figure out if there's a similar method for setting the Icon property to another (non-standard) image file, but I've been unsuccessful with that so far. I hope this helps anyone that stumbles across this in the future.
Take a look at the Ookii.Dialogs. It implements the TaskDialog and others dialogs as well, and have versions targeting WPF and Windows Forms.

(p4 api .NET) Setting multiple ClientOption members

Currently when viewing my client settings, the Options field is "noallwrite noclobber nocompress unlocked nomodtime normdir." I would like to check the compress and rmdir fields using the p4 api. There is code to do each individually:
client.Options = ClientOption.Compress;
client.Options = ClientOption.RmDir;
However, after looking at the api and online, I cannot find a way to do both at the same time. I can easily go into P4V and check both of these boxes, but I am trying to do it using the p4 api to make setup easier for future workspaces/clients. Any ideas?
Since the options in p4 options are flags
[Flags]
public enum ClientOption
{
None = 0,
AllWrite = 1,
Clobber = 2,
Compress = 4,
Locked = 8,
ModTime = 16,
RmDir = 32,
}
You can pile them them up to get the expected result like this
P4.Client client = this.Repository.GetClient(clientname, null);
string options= "noallwrite clobber nocompress unlocked nomodtime rmdir";
client.Options = new P4.ClientOption();
if (!options.Contains("noallwrite"))
{
client.Options |= P4.ClientOption.AllWrite;
}
if (!options.Contains("noclobber"))
{
client.Options |= P4.ClientOption.Clobber;
}
.....
Hope this helps!.

can not save application settings in .net 3.5

I am creating a application that store basic database connection info like host,user, password and default database name in application settings using User Scope.
I am using .net 3.5 with Visual Studio 2008
I put 4 text boxes in a user control and bound their text property to the application settings individual properties.
//
// textBox_database
//
this.textBox_database.Location = new System.Drawing.Point(103, 101);
this.textBox_database.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.textBox_database.Name = "textBox_database";
this.textBox_database.Size = new System.Drawing.Size(255, 27);
this.textBox_database.TabIndex = 5;
this.textBox_database.Text = global::PHP_Code_Generator_2.Properties.Settings.Default.mysql_database;
//
// textBox_password
//
this.textBox_password.Location = new System.Drawing.Point(103, 69);
this.textBox_password.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.textBox_password.Name = "textBox_password";
this.textBox_password.Size = new System.Drawing.Size(255, 27);
this.textBox_password.TabIndex = 4;
this.textBox_password.Text = global::PHP_Code_Generator_2.Properties.Settings.Default.mysql_password;
this.textBox_password.UseSystemPasswordChar = true;
//
// textBox_user
//
this.textBox_user.Location = new System.Drawing.Point(103, 37);
this.textBox_user.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.textBox_user.Name = "textBox_user";
this.textBox_user.Size = new System.Drawing.Size(255, 27);
this.textBox_user.TabIndex = 7;
this.textBox_user.Text = global::PHP_Code_Generator_2.Properties.Settings.Default.mysql_user;
//
// textBox_server
//
this.textBox_server.Location = new System.Drawing.Point(103, 5);
this.textBox_server.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.textBox_server.Name = "textBox_server";
this.textBox_server.Size = new System.Drawing.Size(255, 27);
this.textBox_server.TabIndex = 6;
this.textBox_server.Text = global::PHP_Code_Generator_2.Properties.Settings.Default.mysql_server;
these text boxes will get user data from users to set their own database info. i have a button that saves the modified info back to the settings file
private void button_save_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Save();
}
but the design is not being saved. any help anyone?
regards,
Anjan
To Cyril: Yes i had the code to assign modified value in properties, but then even the scope was set to "User" it said readonly. So i removed the property assignment codes.
now i brought the code back and restarted VS, it works perfect now :D silly me, i should have try this old procedure before.
Thank you Cyril.
Hmm... I remember having the same problem a few months ago in one of my projects. Unfortunately I don't recall how I solved it.
Some checks...
Try setting the property scope to User in the Project Properties.
In the code you've listed I don't see where you set the property (only see you retrieving the property). Where have you set it?

Categories