I've been working on this one quite a bit and haven't gotten any closer to a solution.
I juut dug up my old copy of the WindowsHookLib again - It's available with source at http://www.codeproject.com/KB/DLL/WindowsHookLib.aspx. This library allows Global Windows Mouse/Keyboard/Clipboard Hooks, which is very useful.
I'm trying to use the Mouse Hook in here to Capture Mouse-Motion (I could use a Timer that always polls Cursor.Position, but I plan on using more features of WindowsHookLib later).
Code as follows:
MouseHook mh = new MouseHook();
mh.InstallHook();
mh.MouseMove += new EventHandler<WindowsHookLib.MouseEventArgs>(mh_MouseMove);
But on the call to InstallHook(), I get an Exception: "The specified Module could not be found". Strange. Searching, I found that someone thought this occurs because a DLL is not in a place included in the Windows PATH variable, and because placing it in system32 didn't help I went the whole hog and translated the thing to C# for inclusion directly in my project (I was curious how it works).
However the error was obstinately persistent, so I dug a bit on this, and found the Code in the Library that is responsible: In InstallHook(), we have
IntPtr hinstDLL = Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]);
this._hMouseHook = UnsafeNativeMethods.SetWindowsHookEx(14, this._mouseProc, hinstDLL, 0);
if (this._hMouseHook == IntPtr.Zero)
{
throw new MouseHookException(new Win32Exception(Marshal.GetLastWin32Error()).Message);
}
And this (after modification and recompile) tells me that what I'm really getting is a Windows error "ERROR_MOD_NOT_FOUND"! Now, Here I'm stumped. Didn't I just compile the Hook Library directly into my project?
(UnsafeMethods.SetWindowsHookEx is just a DllImported Method from user32)
Any Answers, or Prods in the right direction, or any hints, pointers or similar are very much appreciated!
I found when migrating to .NET 4.0 I had to send in IntPtr.Zero for the hMod parameter when the Hook Procedure was in the local assembly. You can refer to the msdn documentation here.
http://msdn.microsoft.com/en-us/library/ms644990%28VS.85%29.aspx
I am also having this problem. I found that it seems to be to do with the version of .Net you are using. .Net 4 you get this error, change to .Net 3.5 and it works.
Expanding on #MichaelWohltman's answer above (no code) here's an exmple of its implementation for Kaeyboard hook:
/// <summary>
/// Installs the keyboard hook for this application.
/// </summary>
public void InstallHook()
{
if (this._hKeyboardHook == IntPtr.Zero)
{
this._keyboardProc = new KeyboardHook.KeyboardMessageEventHandler(KeyboardProc);
IntPtr hinstDLL = Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]);
this._hKeyboardHook = UnsafeNativeMethods.SetWindowsHookEx(UnsafeNativeMethods.WH_KEYBOARD_LL, this._keyboardProc, IntPtr.Zero, 0);
if (this._hKeyboardHook == IntPtr.Zero)
{
// Failed to hook. Throw a HookException
throw new Exception("That fucking exception!");
//int eCode = Marshal.GetLastWin32Error();
//this._keyboardProc = null;
//throw new WindowsHookException(new Win32Exception(eCode).Message);
}
else
{
this.OnStateChanged(new WindowsHookLib.StateChangedEventArgs(this.State));
}
}
}
The line of interest is:
this._hKeyboardHook = UnsafeNativeMethods.SetWindowsHookEx(UnsafeNativeMethods.WH_KEYBOARD_LL, this._keyboardProc, IntPtr.Zero, 0);
note the ItrPtr.Zero replaces hinstDLL
Interestingly, I was having problems with a Framework 3.5 build. It was rather complicated as it was a plugin/class library for another application, but this replacement seemed to solve the problem.
Related
In my Visual Studio extension, I'm going to read the text that is in the navigation bar. Therefore I listen to window created events and from the IVsCodeWindow object I get the IVsDropdownBar to get the current selection in the dropdown bar. This works fine. Then I'm using the following code snippet to extract the text of the current selection:
string text;
barClient.GetEntryText(MembersDropdown, curSelection, out text);
if (hr == VSConstants.S_OK)
{
Debug.WriteLine("Text: " + text);
} else {
Debug.WriteLine("No text found!");
}
However, this does not work. My extension crashes with an unhandled exception in the second line of the code snippet. I read the documentation and could find the following note:
The text buffer returned in ppszText is typically created by the
IVsDropdownBarClient object and the buffer must persist for the life
of the IVsDropdownBarClient object. If you are implementing this
interface in managed code and you need to have the string disposed of
by the caller, implement the IVsCoTaskMemFreeMyStrings interface on
the IVsDropdownBarClient interface.
I assume that this is part of my problem, but I can't really understand what I have to change in my code to get it working. Any hints?
I'm pretty sure now that the Visual Studio SDK Interop DLLs have the wrong marshalling information for IVsDropDownbarClient.GetEntryText and that there's no way to call that method using that interface.
The best workaround I've found so far is:
Use the tlbimp tool to generate an alternate Interop DLL for textmgr. (You can safely ignore the dozens of warnings including the one about GetTextEntry.)
tlbimp "c:\Program Files (x86)\Microsoft Visual Studio 11.0\VSSDK\VisualStudioIntegration\Common\Inc\textmgr.tlb"
(Optional) If you're using source control, you'll probably want to copy the resulting file (TextManagerInternal.dll) to a subdirectory of your extension project and check it in as an external dependency.
In your Visual Studio extension project, add a reference to the file (TextManagerInternal.dll).
Add the following method that should properly handle the string marshalling.
static public string HackHackGetEntryText(IVsDropdownBarClient client, int iCombo, int iIndex)
{
TextManagerInternal.IVsDropdownBarClient hackHackClient = (TextManagerInternal.IVsDropdownBarClient) client;
string szText = null;
IntPtr ppszText = IntPtr.Zero;
try
{
ppszText = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr)));
if(ppszText == IntPtr.Zero)
throw new Exception("Unable to allocate memory for IVsDropDownBarClient.GetTextEntry string marshalling.");
hackHackClient.GetEntryText(iCombo, iIndex, ppszText);
IntPtr pszText = Marshal.ReadIntPtr(ppszText);
szText = Marshal.PtrToStringUni(pszText);
}
finally
{
if(ppszText != IntPtr.Zero)
Marshal.FreeCoTaskMem(ppszText);
}
return szText;
}
}
I have been at this for quite a while. I am using C# for Serious Game Programing, and am working on the SoundManager code found in Chapter 9 of the book, if you want an exact reference. The Code is setting up a sound manager using OpenAl, and I am having a problem with the Alut interface (if that is the right word for what it is). Here is the code that I am working on:
public void LoadSound(string soundId, string path)
{
int buffer = -1;
Al.alGenBuffers(1, out buffer);
int errorCode = Al.alGetError();
System.Diagnostics.Debug.Assert(errorCode == Al.AL_NO_ERROR);
int format;
float frequency;
int size;
System.Diagnostics.Debug.Assert(File.Exists(path));
IntPtr data = Alut.alutLoadMemoryFromFile(path, out format, out size, out frequency);
int errorCode2 = Alut.alutGetError();
//string errorCodeString = Alut.alutGetErrorString(errorCode2);
//System.Diagnostics.Debug.Assert(errorCode2 != Alut.ALUT_ERROR_NO_ERROR);
//System.Diagnostics.Debug.Assert(data != IntPtr.Zero));
//System.Diagnostics.Debug.Write(errorCode2);
Al.alBufferData(buffer, format, data, size, (int)frequency);
_soundIdentifier.Add(soundId, new SoundSource(buffer, path));
}
The issue is this line right here: System.Diagnostics.Debug.Assert(data != IntPtr.Zero));. When this line is not commented out, it always fails. I did have it work, and do not know what I did to change it, and it stopped working. I have posted about this on another post here: Load sound problem in OpenAL
I have looked all over, and from what I can gather, the issue is with the way that OpenAl is working on my system. To that end, I have uninstalled the Tao Framework that I am using to run OpenAl, and reinstalled. I have also done a system restore to as many points as I have back. I have thought about nuking my whole system, and starting fresh, but a want to avoid this if I can.
I Also have found this link http://distro.ibiblio.org/rootlinux/rootlinux-ports/more/freealut/freealut-1.1.0/doc/alut.html#ErrorHandling that has helped me understand more about Alut, but have been unable to get an alut.dll from it, and cannot get any errors to display. This code:
int errorCode2 = Alut.alutGetError();
//string errorCodeString = Alut.alutGetErrorString(errorCode2);
//System.Diagnostics.Debug.Assert(errorCode2 != Alut.ALUT_ERROR_NO_ERROR);
System.Diagnostics.Debug.Write(errorCode2);
Is my attempt to find out the exact error. If I write the code like:
int errorCode2 = Alut.alutGetError();
//string errorCodeString = Alut.alutGetErrorString(errorCode2);
System.Diagnostics.Debug.Assert(errorCode2 != Alut.ALUT_ERROR_NO_ERROR);
System.Diagnostics.Debug.Write(errorCode2);
I may be using the code all wrong to the find the exact error, as I am still learning c#.
Here is what I am looking for:
1)Is this a syntax error or an error with my system
2)If it is an error in my system, are there files that I am not removing when I try to do an uninstall of OpenAL to refresh all the files.
3)How do I get the alutGetError() code to display in such a way that I can actually read what it is.
Thank you for any help beforehand.
I recently ran into the same problem while going through that book and was able to figure it out by logging the error to the output window, notice I through the console.writeline in there.
After doing that I checked the output window which gave me the error code 519. After looking all over I saw a few forum posts recommending I re-install openAl to fix this issue which did the trick, all the links I found didn't work to the download so I had to hunt around but softTonic had the one that worked for me on my windows 7 machine http://openal.en.softonic.com/download
IntPtr data = Alut.alutLoadMemoryFromFile(path, out format, out size, out frequency);
var error= Alut.alutGetError();
Console.WriteLine(error);
//System.Diagnostics.Debug.Assert(data != IntPtr.Zero);
Hope this helps,
helpdevelop
This is my code that throws an exception, it just randomly started today here is the photo :
Here is the whole page code and the error exception :
public frmWFDocumentDetail()
{
InitializeComponent();
NavigationInTransition navigateInTransition = new NavigationInTransition();
navigateInTransition.Backward = new TurnstileTransition { Mode = TurnstileTransitionMode.BackwardIn };
navigateInTransition.Forward = new TurnstileTransition { Mode = TurnstileTransitionMode.ForwardIn };
NavigationOutTransition navigateOutTransition = new NavigationOutTransition();
navigateOutTransition.Backward = new TurnstileTransition { Mode = TurnstileTransitionMode.BackwardOut };
navigateOutTransition.Forward = new TurnstileTransition { Mode = TurnstileTransitionMode.ForwardOut };
TransitionService.SetNavigationInTransition(this, navigateInTransition);
TransitionService.SetNavigationOutTransition(this, navigateOutTransition);
DataContext = App.ViewModel_WFDocumentDetailItems;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//**this is how you pass parameters through to a new page**//
string processID = "-1";
string processName = "";
NavigationContext.QueryString.TryGetValue("processID", out processID);
NavigationContext.QueryString.TryGetValue("processName", out processName);
App.ViewModel_WFDocumentHeaderItems.LoadData("johnny", processID);
App.ViewModel_WFDocumentDetailItems.LoadData("johnny");
}
and the access violation :
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory
is corrupt.
I have read up on it, some people say it is nvidia network manager, and some people say I must set some setting like Suppress JIT optimization , and ignore gpu memory if value isn't changed... but nothing works? Can anyone please please send me in the right direction?
As requested , the full stack
i used the setting taylorjohnl gave me "Debug -> Options and Settings -> Debugging -> General -> Enable Just My Code",and then the error went right to the piece of xaml that was a syntax error, and boom fixed it and app works again :) so violation error for me was basically a reference error, hope this can help other people as well, also use expression blend in silverlight to debug xaml in the UI
I had a similar problem which in the end was resolved by submitting crash dump to MS Tech Support. Here is their response:
The gist is that The crash is a known bug in the version 5.0 of comctl32.dll (Windows Common Controls), which ships with the Windows OS. This bug will not be fixed in version 5.0 of the common controls, because that version was for applications existing prior to Windows XP. It has since been fixed in version 6.0 of comctl32.dll, which is included with Windows XP and later. Note that both versions of comctl32.dll (5.0 and 6.0) are included with every version of Windows since Windows XP. The older one is just there for backwards compatibility purposes for very old applications.
To resolve the problem, you need to change the application to have it opt into version 6.0 of comctl32.dll. Within a Windows Forms application, this is done by calling into the Application.EnableVisualStyles method at startup of the application. If you are developing within a C# project, then you can do this by adding the call prior to your Application.Run call within your application's entry point. For example:
[STAThread]
static void Main()
{
Application.EnableVisualStyles(); //Add this line
Application.Run(new Form1());
}
If you are in a Visual Basic .Net project, you can opt into this by going to your project properties, and then selecting the "Enable Application Framework" and "Enable XP Visual Styles" checkboxes on the Application property page.
Once you do this, it should resolve this particular access violation.
what is code in the InitializeComponent()? there is some class refer to null in it, (mostly is a event handler). once it is trigger, it will report AccessViolation.
I am attempting to implement a Language Service in a VSPackage using the MPF, and it's not working quite as I understand it should.
I have several implementations already, such as ParseSource parsing the input file with a ParseRequest. However, when it finds an error, it adds it with AuthoringSink.AddError. The documentation for this implies it adds it to the Error List for me; it doesn't.
I also have a simple MySource class, a subclass of Source. I return this new class with an overridden LanguageService.CreateSource method. The documentation for OnCommand says it's fired 'when a command is entered'. However, it's not.
There's obviously some intermediate step which I haven't done correctly. I've already rambled enough, so I'll be glad to give any additional details by request.
Any clarification is much appreciated.
For the AuthoringSink error list question, I use this behavior in my Language Service. In ParseSource, the ParseRequest class has an AuthoringSink. You can also create a new ErrorListProvider if you want to work outside of the parser's behavior. Here is some example code:
error_list = new ErrorListProvider(this.Site);
error_list.ProviderName = "MyLanguageService Errors";
error_list.ProviderGuid = new Guid(this.errorlistGUIDstring.);
}
ErrorTask task = new ErrorTask();
task.Document = filename;
task.CanDelete = true;
task.Category = TaskCategory.CodeSense;
task.Column = column;
task.Line = line;
task.Text = message;
task.ErrorCategory = TaskErrorCategory.Error;
task.Navigate += NavigateToParseError;
error_list.Tasks.Add(task);
I hope this was helpful.
OnCommand should be firing every time there is a command, in your MySource class you can do something like this (pulled from working code):
public override void OnCommand(IVsTextView textView, VsCommands2K command, char ch)
{
if (textView == null || this.LanguageService == null
|| !this.LanguageService.Preferences.EnableCodeSense)
return;
if (command == Microsoft.VisualStudio.VSConstants.VSStd2KCmdID.TYPECHAR)
{
if (char.IsLetterOrDigit(ch))
{
//do something cool
}
}
base.OnCommand(textView, command, ch);
}
If that doesn't work double check that CodeSense = true in your ProvideLanguageService attribute when you setup your LanguageService package. A whole lot of what is cool to do in the LanguageService requires these attributes to be correctly turned on. Some even give cool behaviors for free!
Another thing to be careful of is that some behaviors like colorizer don't function correctly in the hive in my experience. I don't think these were ones that gave me trouble, but I implemented these a couple of years ago so I'm mostly just looking back at old code.
AuthoringSink.AddError only adds errors to the error list if ParseRequest.Reason is ParseReason.Check. When your ParseSource function attempts to add errors while parsing for any other ParseReason, nothing will happen.
It's possible that your language service is never calling ParseSource with this ParseReason. As far as I know, the only way to get a ParseReason of Check (outside of manually calling BeginParse or ParseSource yourself) is to proffer your service with an idle timer.
I'm try to use Vista TaskDialog Wrapper and Emulator and I'm getting the following exception:
"Unable to find an entry point named 'TaskDialogIndirect' in DLL 'ComCtl32'."
...in a simple Console application:
class Program
{
[STAThread]
static void Main(string[] args)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
PSTaskDialog.cTaskDialog.MessageBox(
"MessageBox Title",
"The main instruction text for the message box is shown here.",
"The content text for the message box is shown here and the text willautomatically wrap as needed.",
PSTaskDialog.eTaskDialogButtons.YesNo,
PSTaskDialog.eSysIcons.Information
);
}
}
What am I doing wrong?
UPDATE:
Actually, I'm working on an Excel plugin using excel-dna. How can I control what dll Excel loads?
http://exceldna.codeplex.com/discussions/286990#post728888
I haven't been at Office programming in a while, but my guess is that Excel loads both versions of comctl32, so you may need to use the Activation Context API to direct your code to the version that includes TaskDialog. Some ideas for fixing the problem (not solutions as such):
For test purposes, make a temporary enumeration of all modules in the active process - just to check if 6.10 is actually loaded (see below for a simple example of such an enumeration, albeit with a different intent).
Use the Activation Context API to get to the right version. Example of use from C# (for enabling themes by way of comctl32 6.0) here.
Alternatively (I never actually got this to work reliably in a WPF application I worked on), make a dialog abstraction class, which falls back to MessageDlg depending on the version available to you. There may be better ways of doing the check, but...:
FileVersionInfo version = ProcessUtils.GetLoadedModuleVersion("comctl32.dll");
if (version != null && version.FileMajorPart >= 6 && version.FileMinorPart >= 1)
{
// We can use TaskDialog...
}
else
{
// Use old style MessageBox
}
The enumeration of modules:
internal static FileVersionInfo GetLoadedModuleVersion(string name)
{
Process process = Process.GetCurrentProcess();
foreach (ProcessModule module in process.Modules)
{
if (module.ModuleName.ToLower() == name)
{
return module.FileVersionInfo;
}
return null;
}
}
In addition to what all the others are saying: This error will disappear if you set the ForceEmulationMode on PSTaskDialog to true.