no sound heard while playing a MIDI file in C#.Net - c#

I use this code to play a MIDI file for my game, but I can not hear any sound from my speakers. Would you help me? It's kind of an emergency, please...
My speakers are turned on ;)
[DllImport("winmm.dll", EntryPoint="mciSendStringA")]
private static extern long mciSendString(string lpstrCommand, string lpstrReturnString, long uReturnLength, long hwndCallback);
public static long PlayMidiFile(string MidiFile)
{
long lRet = -1;
if (File.Exists(MidiFile))
{
lRet = mciSendString("stop midi", "", 0, 0);
lRet = mciSendString("close midi", "", 0, 0);
lRet = mciSendString(("open sequencer!"
+ (MidiFile + " alias midi")), "", 0, 0);
lRet = mciSendString("play midi", "", 0, 0);
return lRet;
}
else
{
//Error Message
return lRet;
}
}

I am not really sure about your implementation of winmm.dll but I have a tested and working code for it.
I got the source code from this open source project: Tea Timer.
The implementation of the code is pretty straight forward as below. Hope it helps.
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace TeaTimer
{
/// <summary>
/// MCIPlayer is based off code by Slain.
/// Found here: http://www.sadeveloper.net/Articles_View.aspx?articleID=212
/// </summary>
public class MCIPlayer
{
private static readonly string sAlias="TeaTimerAudio";
[DllImport("winmm.dll")]
private static extern long mciSendString(string strCommand,StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback);
[DllImport("Winmm.dll")]
private static extern long PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags);
public static void Play(string sFile)
{
_Open(sFile);
_Play();
}
public static void Stop()
{
_Close();
}
private static void _Open(string sFileName)
{
if(_Status()!="")
_Close();
string sCommand = "open \"" + sFileName + "\" alias "+sAlias;
mciSendString(sCommand, null, 0, IntPtr.Zero);
}
private static void _Close()
{
string sCommand = "close "+sAlias;
mciSendString(sCommand, null, 0, IntPtr.Zero);
}
private static void _Play()
{
string sCommand = "play "+sAlias;
mciSendString(sCommand, null, 0, IntPtr.Zero);
}
private static string _Status()
{
StringBuilder sBuffer = new StringBuilder(128);
mciSendString("status "+sAlias+" mode", sBuffer, sBuffer.Capacity, IntPtr.Zero);
return sBuffer.ToString();
}
}
}
EDIT: This is how you play and stop a music file:
public static void playSound(string sFile)
{
//WavPlay.WavPlayer.Play(sFile);
MCIPlayer.Play(sFile);
}
public static void stopSound()
{
//WavPlay.WavPlayer.StopPlay();
MCIPlayer.Stop();
}

I used to use the definition...
[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
public static extern void mciSendStringA(string lpstrCommand, string lpstrReturnString, long uReturnLength, long hwndCallback);
...in .Net 3.5 but in .Net 4.0 is gave me and unbalanced pinvoke exception! I fixed it by using this instead...
[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
public static extern void mciSendStringA(string lpstrCommand, string lpstrReturnString, int uReturnLength, IntPtr hwndCallback);
...and passing in IntPtr.Zero as the last param.
The only difference is the uReturnLength is an int (and not a long) and hwndCallback is a IntPtr (and not a long).
Hope this helps...

Related

How to get IMEI from IOS device using C#

I need to read out the IMEI of an IOS device using C#...
Is this even possible in C#/Xamarin?
Or is there another value that i can use to identify a device?
Some device identifiers are now impossible to be obtained from public APIs of iOS:
IMSI - International Mobile Subscriber Identity (SIM card number)
IMEI - International Mobile Equipment Identity (Device ID)
UDID - Unique Device Identifier for Apple iDevices
MAC address - Media Access Control Address (Network address)
Take a look here:
http://studyswift.blogspot.gr/2015/12/asidentifiermanager-get-idfv-vendor.html
If you could use any of the provided IDs the code is in Swift but if you use C# / Xamarin it won't be difficult to convert.
Hope this helps
I've also tried to find a way to capture the IMEI, but I believe this is not possible. The only way I solved it was to use this code, it returns serial number
public class IosDevice
{
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern uint IOServiceGetMatchingService(uint masterPort, IntPtr matching);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern IntPtr IOServiceMatching(string s);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern IntPtr IORegistryEntryCreateCFProperty(uint entry, IntPtr key, IntPtr allocator, uint options);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern int IOObjectRelease(uint o);
public string GetIdentifier()
{
string serial = string.Empty;
uint platformExpert = IOServiceGetMatchingService(0, IOServiceMatching("IOPlatformExpertDevice"));
if (platformExpert != 0)
{
NSString key = (NSString)"IOPlatformSerialNumber";
IntPtr serialNumber = IORegistryEntryCreateCFProperty(platformExpert, key.Handle, IntPtr.Zero, 0);
if (serialNumber != IntPtr.Zero)
{
serial = NSString.FromHandle(serialNumber);
}
IOObjectRelease(platformExpert);
}
return serial;
}
}
In case someone wants to get vid, pid of an USB Device in MacOS
public class OsxDeviceDiscovery
{
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern int IOServiceGetMatchingService(int masterPort, IntPtr matching);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern int IOServiceGetMatchingServices(int masterPort, IntPtr matching, out IntPtr iterator);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern IntPtr IOServiceMatching(string name);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern IntPtr IORegistryEntryCreateCFProperty(int entry, IntPtr key, IntPtr allocator, uint options);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern int IOObjectRelease(int o);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern int IOIteratorNext(IntPtr iterator);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern bool CFNumberGetValue(IntPtr number,long type, ref long value);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern int CFNumberGetType(IntPtr number);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern bool CFStringGetCString(IntPtr stringRef, byte[] str, int size, int encoding);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
private static extern int IORegisterEntryCreateIterator(IntPtr entry, IntPtr plane, int options, out IntPtr iterator);
public static string GetIdentifier()
{
string deviceName = string.Empty;
IntPtr matchingNodes;
int platformExpert = IOServiceGetMatchingServices(0, IOServiceMatching("IOUSBDevice"), out matchingNodes);
int node = -1;
while ((node = IOIteratorNext(matchingNodes)) != 0)
{
long vendorID = 0;
long productID = 0;
long locationId = 0;
NSString key = (NSString)"idVendor";
IntPtr proRef = IORegistryEntryCreateCFProperty(node, key.Handle, IntPtr.Zero, 0);
if (proRef != IntPtr.Zero)
{
long type = CFNumberGetType(proRef);
CFNumberGetValue(proRef, type, ref vendorID);
}
key = (NSString)"idProduct";
proRef = IORegistryEntryCreateCFProperty(node, key.Handle, IntPtr.Zero, 0);
if (proRef != IntPtr.Zero)
{
long type = CFNumberGetType(proRef);
CFNumberGetValue(proRef, type, ref productID);
}
if (vendorID != 0x1234 || productID != 0x5678)
{
IOObjectRelease(node);
continue;
}
key = (NSString)"locationID";
proRef = IORegistryEntryCreateCFProperty(node, key.Handle, IntPtr.Zero, 0);
if (proRef != IntPtr.Zero)
{
long type = CFNumberGetType(proRef);
CFNumberGetValue(proRef, type, ref locationId);
}
key = (NSString)"kUSBSerialNumberString";
proRef = IORegistryEntryCreateCFProperty(node, key.Handle, IntPtr.Zero, 0);
if (proRef != IntPtr.Zero)
{
byte[] byteArray = new byte[20];
CFStringGetCString(proRef, byteArray, 20, 0x0600);
string serialNumber = System.Text.Encoding.UTF8.GetString(byteArray);
deviceName = "/dev/cu.usbmodem" + serialNumber;
}
IOObjectRelease(node);
}
return deviceName;
}
}

C# deezer native api: adapting to C#

I'm trying to use a C# class that wraps C++ native api into CLI C# class.
It seems that there are some problems (it really near to be working) and would like some help to find the problem.
Here is the wrapper's code
using System;
using System.Collections;
using System.Runtime.InteropServices;
// make this binding dependent on WPF, but easier to use
using System.Windows.Threading;
// http://www.codeproject.com/Articles/339290/PInvoke-pointer-safety-Replacing-IntPtr-with-unsaf
namespace Deezer
{
#region Enums
public enum CONNECT_EVENT_TYPE
{
UNKNOWN, /**< Connect event has not been set yet, not a valid value. */
USER_OFFLINE_AVAILABLE, /**< User logged in, and credentials from offline store are loaded. */
USER_ACCESS_TOKEN_OK, /**< (Not available) dz_connect_login_with_email() ok, and access_token is available */
USER_ACCESS_TOKEN_FAILED, /**< (Not available) dz_connect_login_with_email() failed */
USER_LOGIN_OK, /**< Login with access_token ok, infos from user available. */
USER_LOGIN_FAIL_NETWORK_ERROR, /**< Login with access_token failed because of network condition. */
USER_LOGIN_FAIL_BAD_CREDENTIALS, /**< Login with access_token failed because of bad credentials. */
USER_LOGIN_FAIL_USER_INFO, /**< Login with access_token failed because of other problem. */
USER_LOGIN_FAIL_OFFLINE_MODE, /**< Login with access_token failed because we are in forced offline mode. */
USER_NEW_OPTIONS, /**< User options have just changed. */
ADVERTISEMENT_START, /**< A new advertisement needs to be displayed. */
ADVERTISEMENT_STOP, /**< An advertisement needs to be stopped. */
};
public enum PLAYER_COMMANDS
{
UNKNOWN, /**< Player command has not been set yet, not a valid value. */
START_TRACKLIST, /**< A new tracklist was loaded and a track played. */
JUMP_IN_TRACKLIST, /**< The user jump into a new song in the current tracklist. */
NEXT, /**< Next button. */
PREV, /**< Prev button. */
DISLIKE, /**< Dislike button. */
NATURAL_END, /**< Natural end. */
RESUMED_AFTER_ADS, /**< Reload after playing an ads. */
}
public enum TRACKLIST_AUTOPLAY_MODE
{
MODE_UNKNOWN,
MANUAL,
MODE_ONE,
MODE_ONE_REPEAT,
MODE_NEXT,
MODE_NEXT_REPEAT,
MODE_RANDOM,
MODE_RANDOM_REPEAT,
};
public enum PLAYER_EVENT_TYPE
{
UNKNOWN, /**< Player event has not been set yet, not a valid value. */
// Data access related event.
LIMITATION_FORCED_PAUSE, /**< Another deezer player session was created elsewhere, the player has entered pause mode. */
// Track selection related event.
PLAYLIST_TRACK_NOT_AVAILABLE_OFFLINE,/**< You're offline, the track is not available. */
PLAYLIST_TRACK_NO_RIGHT, /**< You don't have the right to render this track. */
PLAYLIST_TRACK_RIGHTS_AFTER_AUDIOADS,/**< You have right to play it, but you should render an ads first :
- Use dz_player_event_get_advertisement_infos_json().
- Play an ad with dz_player_play_audioads().
- Wait for #DZ_PLAYER_EVENT_RENDER_TRACK_END.
- Use dz_player_play() with previous track or DZ_PLAYER_PLAY_CMD_RESUMED_AFTER_ADS (to be done even on radios for now).
*/
PLAYLIST_SKIP_NO_RIGHT, /**< You're on a radio, and you had no right to do skip. */
PLAYLIST_TRACK_SELECTED, /**< A track is selected among the ones available on the server, and will be fetched and read. */
PLAYLIST_NEED_NATURAL_NEXT, /**< We need a new natural_next action. */
// Data loading related event.
MEDIASTREAM_DATA_READY, /**< Data is ready to be introduced into audio output (first data after a play). */
MEDIASTREAM_DATA_READY_AFTER_SEEK, /**< Data is ready to be introduced into audio output (first data after a seek). */
// Play (audio rendering on output) related event.
RENDER_TRACK_START_FAILURE, /**< Error, track is unable to play. */
RENDER_TRACK_START, /**< A track has started to play. */
RENDER_TRACK_END, /**< A track has stopped because the stream has ended. */
RENDER_TRACK_PAUSED, /**< Currently on paused. */
RENDER_TRACK_SEEKING, /**< Waiting for new data on seek. */
RENDER_TRACK_UNDERFLOW, /**< Underflow happened whilst playing a track. */
RENDER_TRACK_RESUMED, /**< Player resumed play after a underflow or a pause. */
RENDER_TRACK_REMOVED, /**< Player stopped playing a track. */
};
#endregion
#region Delegates
// called with userdata Dispatcher on connect events
public delegate void ConnectOnEventCb(Connect connect, ConnectEvent connectEvent, DispatcherObject userdata);
public delegate void PlayerOnEventCb(Player player, PlayerEvent playerEvent, DispatcherObject userdata);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
unsafe public delegate void libcConnectOnEventCb(CONNECT* libcConnect, CONNECT_EVENT* libcConnectEvent, IntPtr userdata);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
unsafe public delegate bool libcAppCrashDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
unsafe public delegate void libcPlayerOnEventCb(PLAYER* libcPlayer, PLAYER_EVENT* libcPlayerEvent, IntPtr userdata);
#endregion
#region Structures
unsafe public struct CONNECT_EVENT { };
unsafe public struct UTF8STRING { };
unsafe public struct CONNECT { };
unsafe public struct PLAYER_EVENT { };
unsafe public struct PLAYER { };
#endregion
#region Imports
#endregion
// to be in sync with dz_connect_configuration
[StructLayout(LayoutKind.Sequential)]
public class ConnectConfig
{
public string ccAppId;
public string ccAppSecret;
public string ccUserProfilePath;
public Dispatcher ccConnectUserdata;
public ConnectOnEventCb ccConnectEventCb;
}
public class ConnectEvent
{
internal CONNECT_EVENT_TYPE eventType;
/* two design strategies:
* - we could keep a reference to CONNECT_EVENT* with dz_object_retain and call method on the fly
* - we extract all info in constructor and have pure managed object
*
* here we keep the second option, because we have to have a managed object anyway, and it's
* a lot fewer unsafe method to expose, even though it's making a lot of calls in the constructor..
*/
public unsafe static ConnectEvent newFromLibcEvent(CONNECT_EVENT* libcConnectEventHndl)
{
CONNECT_EVENT_TYPE eventType;
unsafe
{
eventType = dz_connect_event_get_type(libcConnectEventHndl);
}
switch (eventType)
{
case CONNECT_EVENT_TYPE.USER_ACCESS_TOKEN_OK:
string accessToken;
unsafe
{
IntPtr libcAccessTokenString = dz_connect_event_get_access_token(libcConnectEventHndl);
accessToken = Marshal.PtrToStringAnsi(libcAccessTokenString);
}
return new NewAccessTokenConnectEvent(accessToken);
default:
return new ConnectEvent(eventType);
}
}
public ConnectEvent(CONNECT_EVENT_TYPE eventType)
{
this.eventType = eventType;
}
public CONNECT_EVENT_TYPE GetEventType()
{
return eventType;
}
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe CONNECT_EVENT_TYPE dz_connect_event_get_type(CONNECT_EVENT* dzConnectEvent);
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe IntPtr dz_connect_event_get_access_token(CONNECT_EVENT* dzConnectEvent);
}
public class NewAccessTokenConnectEvent : ConnectEvent
{
string accessToken;
public NewAccessTokenConnectEvent(string accessToken)
: base(CONNECT_EVENT_TYPE.USER_ACCESS_TOKEN_OK)
{
this.accessToken = accessToken;
}
public string GetAccessToken()
{
return accessToken;
}
}
unsafe public class Connect
{
// hash
static Hashtable refKeeper = new Hashtable();
internal unsafe CONNECT* libcConnectHndl;
internal ConnectConfig connectConfig;
public unsafe Connect(ConnectConfig cc)
{
NativeMethods.LoadClass();
//ConsoleHelper.AllocConsole();
// attach a console to parent process (launch from cmd.exe)
//ConsoleHelper.AttachConsole(-1);
CONNECT_CONFIG libcCc = new CONNECT_CONFIG();
connectConfig = cc;
IntPtr intptr = new IntPtr(this.GetHashCode());
refKeeper[intptr] = this;
libcCc.ccAppId = cc.ccAppId;
//libcCc.ccAppSecret = cc.ccAppSecret;
libcCc.ccUserProfilePath = UTF8Marshaler.GetInstance(null).MarshalManagedToNative(cc.ccUserProfilePath);
libcCc.ccConnectEventCb = delegate (CONNECT* libcConnect, CONNECT_EVENT* libcConnectEvent, IntPtr userdata)
{
Connect connect = (Connect)refKeeper[userdata];
ConnectEvent connectEvent = ConnectEvent.newFromLibcEvent(libcConnectEvent);
Dispatcher dispather = connect.connectConfig.ccConnectUserdata;
dispather.Invoke(connect.connectConfig.ccConnectEventCb, connect, connectEvent, connect.connectConfig.ccConnectUserdata);
};
libcConnectHndl = dz_connect_new(libcCc);
UTF8Marshaler.GetInstance(null).CleanUpNativeData(libcCc.ccUserProfilePath);
}
public int Start()
{
int ret;
ret = dz_connect_activate(libcConnectHndl, new IntPtr(this.GetHashCode()));
return ret;
}
public string DeviceId()
{
IntPtr libcDeviceId = dz_connect_get_device_id(libcConnectHndl);
if (libcDeviceId == null)
{
return null;
}
return Marshal.PtrToStringAnsi(libcDeviceId);
}
public int SetAccessToken(string accessToken)
{
int ret;
ret = dz_connect_set_access_token(libcConnectHndl, IntPtr.Zero, IntPtr.Zero, accessToken);
return ret;
}
public int SetSmartCache(string path, int quotaKb)
{
int ret;
ret = dz_connect_cache_path_set(libcConnectHndl, IntPtr.Zero, IntPtr.Zero, path);
ret = dz_connect_smartcache_quota_set(libcConnectHndl, IntPtr.Zero, IntPtr.Zero, quotaKb);
return ret;
}
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe CONNECT* dz_connect_new(
[In, MarshalAs(UnmanagedType.LPStruct)]
CONNECT_CONFIG lpcc);
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe IntPtr dz_connect_get_device_id(
CONNECT* dzConnect);
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe int dz_connect_activate(
CONNECT* dzConnect, IntPtr userdata);
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe int dz_connect_set_access_token(
CONNECT* dzConnect, IntPtr cb, IntPtr userdata, string access_token);
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe int dz_connect_cache_path_set(
CONNECT* dzConnect, IntPtr cb, IntPtr userdata,
[MarshalAs(UnmanagedType.CustomMarshaler,
MarshalTypeRef=typeof(UTF8Marshaler))]
string local_path);
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe int dz_connect_smartcache_quota_set(
CONNECT* dzConnect, IntPtr cb, IntPtr userdata,
int quota_kB);
}
public class PlayerEvent
{
internal PLAYER_EVENT_TYPE eventType;
/* two design strategies:
* - we could keep a reference to PLAYER_EVENT* with dz_object_retain and call method on the fly
* - we extract all info in constructor and have pure managed object
*
* here we keep the second option, because we have to have a managed object anyway, and it's
* a lot fewer unsafe method to expose, even though it's making a lot of calls in the constructor..
*/
public unsafe static PlayerEvent newFromLibcEvent(PLAYER_EVENT* libcPlayerEventHndl)
{
PLAYER_EVENT_TYPE eventType;
unsafe
{
eventType = dz_player_event_get_type(libcPlayerEventHndl);
}
switch (eventType)
{
default:
return new PlayerEvent(eventType);
}
}
public PlayerEvent(PLAYER_EVENT_TYPE eventType)
{
this.eventType = eventType;
}
public PLAYER_EVENT_TYPE GetEventType()
{
return eventType;
}
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe PLAYER_EVENT_TYPE dz_player_event_get_type(PLAYER_EVENT* dzPlayerEvent);
}
unsafe public class Player
{
// hash
static Hashtable refKeeper = new Hashtable();
internal unsafe PLAYER* libcPlayerHndl;
internal Connect connect;
internal libcPlayerOnEventCb eventcb;
public unsafe Player(Connect connect, object observer)
{
IntPtr intptr = new IntPtr(this.GetHashCode());
refKeeper[intptr] = this;
libcPlayerHndl = dz_player_new(connect.libcConnectHndl);
this.connect = connect;
}
public int Start(PlayerOnEventCb eventcb)
{
int ret;
ret = dz_player_activate(libcPlayerHndl, new IntPtr(this.GetHashCode()));
this.eventcb = delegate (PLAYER* libcPlayer, PLAYER_EVENT* libcPlayerEvent, IntPtr userdata)
{
Player player = (Player)refKeeper[userdata];
PlayerEvent playerEvent = PlayerEvent.newFromLibcEvent(libcPlayerEvent);
Dispatcher dispather = player.connect.connectConfig.ccConnectUserdata;
dispather.Invoke(eventcb, player, playerEvent, connect.connectConfig.ccConnectUserdata);
};
ret = dz_player_set_event_cb(libcPlayerHndl, this.eventcb);
return ret;
}
public int LoadStream(string url)
{
int ret;
ret = dz_player_load(libcPlayerHndl, IntPtr.Zero, IntPtr.Zero, url);
return ret;
}
public int Play(int idx, PLAYER_COMMANDS cmd)
{
int ret;
ret = dz_player_play(libcPlayerHndl, IntPtr.Zero, IntPtr.Zero, cmd, TRACKLIST_AUTOPLAY_MODE.MODE_ONE, idx);
return ret;
}
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe PLAYER* dz_player_new(CONNECT* lpcc);
//static extern unsafe PLAYER* dz_player_new(CONNECT* lpcc, IntPtr userdata);
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe int dz_player_set_event_cb(PLAYER* lpcc, libcPlayerOnEventCb cb);
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe int dz_player_activate(PLAYER* dzPlayer, IntPtr userdata);
//static extern unsafe int dz_player_activate(PLAYER* dzPlayer, IntPtr userdata);
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe int dz_player_load(PLAYER* dzPlayer, IntPtr cb, IntPtr userdata, string url);
[DllImport("libdeezer.x64.dll", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe int dz_player_play(PLAYER* dzPlayer, IntPtr cb, IntPtr userdata, PLAYER_COMMANDS cmd, TRACKLIST_AUTOPLAY_MODE mode, int idx);
//static extern unsafe int dz_player_play(PLAYER* dzPlayer, IntPtr cb, IntPtr userdata, int idx, TRACKLIST_AUTOPLAY_MODE mode);
}
[StructLayout(LayoutKind.Sequential)]
public class CONNECT_CONFIG
{
public string ccAppId;
public string ccProductId;
public string ccProductBuildId;
public IntPtr ccUserProfilePath;
public libcConnectOnEventCb ccConnectEventCb;
public string ccAnonymousBlob;
public libcAppCrashDelegate ccAppCrashDelegate;
}
// trick from http://stackoverflow.com/questions/1573724/cpu-architecture-independent-p-invoke-can-the-dllname-or-path-be-dynamic
// but actually SetDllDirectory works better (for pthread.dll)
public static class NativeMethods
{
// call this to load this class
public static void LoadClass()
{
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetDllDirectory(string lpPathName);
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
static extern IntPtr LoadLibrary(string lpFileName);
static NativeMethods()
{
string arch;
string basePath = System.IO.Path.GetDirectoryName(typeof(NativeMethods).Assembly.Location);
if (IntPtr.Size == 4)
arch = "i386";
else
arch = "x86_64";
System.Diagnostics.Debug.WriteLine("using arch: " + arch);
SetDllDirectory(System.IO.Path.Combine(basePath, arch));
#if false // can be used to debug library loading
IntPtr hExe = LoadLibrary("libdeezer.x64.dll");
if (hExe == IntPtr.Zero)
{
Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
System.Console.WriteLine("exception:" + ex);
throw ex;
}
#endif
}
}
// http://stackoverflow.com/questions/10415807/output-console-writeline-from-wpf-windows-applications-to-actual-console
public class ConsoleHelper
{
/// <summary>
/// Allocates a new console for current process.
/// </summary>
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
[DllImport("Kernel32.dll")]
public static extern bool AttachConsole(int processId);
/// <summary>
/// Frees the console.
/// </summary>
[DllImport("kernel32.dll")]
public static extern Boolean FreeConsole();
}
// http://www.codeproject.com/Articles/138614/Advanced-Topics-in-PInvoke-String-Marshaling
public class UTF8Marshaler : ICustomMarshaler
{
static UTF8Marshaler static_instance;
// maybe we could play with WideCharToMultiByte too and avoid Marshal.Copy
// http://stackoverflow.com/questions/537573/how-to-get-intptr-from-byte-in-c-sharp
/*
Byte[] byNewData = null;
iNewDataLen = NativeMethods.WideCharToMultiByte(NativeMethods.CP_UTF8, 0, cc.ccUserProfilePath, -1, null, 0, IntPtr.Zero, IntPtr.Zero);
Console.WriteLine("iNewDataLen:" + iNewDataLen + " len:" + cc.ccUserProfilePath.Length + " ulen:" + iNewDataLen);
byNewData = new Byte[iNewDataLen];
iNewDataLen = NativeMethods.WideCharToMultiByte(NativeMethods.CP_UTF8, 0, cc.ccUserProfilePath, cc.ccUserProfilePath.Length, byNewData, iNewDataLen, IntPtr.Zero, IntPtr.Zero);
libcCc.ccUserProfilePath = Marshal.UnsafeAddrOfPinnedArrayElement(byNewData, 0);
*/
public IntPtr MarshalManagedToNative(object managedObj)
{
if (managedObj == null)
return IntPtr.Zero;
if (!(managedObj is string))
throw new MarshalDirectiveException(
"UTF8Marshaler must be used on a string.");
// not null terminated
byte[] strbuf = System.Text.Encoding.UTF8.GetBytes((string)managedObj);
IntPtr buffer = Marshal.AllocHGlobal(strbuf.Length + 1);
Marshal.Copy(strbuf, 0, buffer, strbuf.Length);
// write the terminating null
Marshal.WriteByte(buffer + strbuf.Length, 0);
return buffer;
}
public unsafe object MarshalNativeToManaged(IntPtr pNativeData)
{
byte* walk = (byte*)pNativeData;
// find the end of the string
while (*walk != 0)
{
walk++;
}
int length = (int)(walk - (byte*)pNativeData);
// should not be null terminated
byte[] strbuf = new byte[length];
// skip the trailing null
Marshal.Copy((IntPtr)pNativeData, strbuf, 0, length);
string data = System.Text.Encoding.UTF8.GetString(strbuf);
return data;
}
public void CleanUpNativeData(IntPtr pNativeData)
{
Marshal.FreeHGlobal(pNativeData);
}
public void CleanUpManagedData(object managedObj)
{
}
public int GetNativeDataSize()
{
return -1;
}
public static ICustomMarshaler GetInstance(string cookie)
{
if (static_instance == null)
{
return static_instance = new UTF8Marshaler();
}
return static_instance;
}
[DllImport("kernel32.dll")]
public static extern int WideCharToMultiByte(uint CodePage, uint dwFlags,
[MarshalAs(UnmanagedType.LPWStr)] string lpWideCharStr, int cchWideChar,
[MarshalAs(UnmanagedType.LPArray)] Byte[] lpMultiByteStr, int cbMultiByte, IntPtr lpDefaultChar,
IntPtr lpUsedDefaultChar);
public const uint CP_UTF8 = 65001;
}
}
And here is the caller method to play a song :
ConnectConfig dConfig = new ConnectConfig();
dConfig.ccAppId = appId;
dConfig.ccAppSecret = appSecret;
dConfig.ccConnectUserdata = this.Dispatcher;
dConfig.ccUserProfilePath = #"D:\devlocal\dztemp";
Connect dConnect = new Connect(dConfig);
dConnect.SetAccessToken(accesToken);
//dConnect.SetSmartCache(#"D:\devlocal\dztemp", 2000000);
CONNECT_EVENT_TYPE resp = (CONNECT_EVENT_TYPE)dConnect.Start();
String devId = dConnect.DeviceId();
Object dObserver = null;
Player dPlayer = new Player(dConnect, dObserver);
PLAYER_EVENT_TYPE respPlayerStart = (PLAYER_EVENT_TYPE)dPlayer.Start(dPlayerOnEventCb);
PLAYER_EVENT_TYPE respPlayerLoad = (PLAYER_EVENT_TYPE)dPlayer.LoadStream("dzmedia:///track/97206076");
PLAYER_EVENT_TYPE respPlayerPlay = (PLAYER_EVENT_TYPE)dPlayer.Play(0, PLAYER_COMMANDS.NEXT);
First lines seem to be working correctly but:
CONNECT_EVENT_TYPE resp = (CONNECT_EVENT_TYPE)dConnect.Start();
returns a bad value (always the first one of the enum).
String devId = dConnect.DeviceId();
is ok, I have my device token.
dPlayer.Start, dPlayer.LoadStream, dPlayer.Play are returning bad values and there is no sound playing.
You are miscasting the returned value. Most of the functions return dz_error_t (you can find the enum values in deezer-object.h) the enum CONNECT_EVENT_TYPE is mapped on dz_connect_event_t.
I would suggest to create a new enum mapped on dz_error_t and cast with this new enum.
Moreover, as described in http://developers.deezer.com/sdk/native (Section Playing a song) for the moment only DZ_TRACKLIST_AUTOPLAY_MANUAL is supported. So I would suggest to change the dz_player_play call into:
dz_player_play(libcPlayerHndl, IntPtr.Zero, IntPtr.Zero, cmd, TRACKLIST_AUTOPLAY_MODE.MANUAL, idx);
and dPlayer.Play into:
dPlayer.Play(0, PLAYER_COMMANDS.START_TRACKLIST);
If you still have an issue, please also post the traces returned by your application.
Do you have files created in the path provided by ccUserProfilePath ?
If you still have an issue, be sure you have right to play the song by trying to play it with your Internet browser at this address http://www.deezer.com/track/97206076.
Regards,
Cyril

hide tiles of Windows 8.1 in c# programmatically

I have to extend a terminal server software in order to work with windows 8.1.
The scenario is a follows:
Two PCs: on one runs the client software on the other one runs the server.
The operating system of the server is Windows 8.1
When the user presses a button on the client PC it opens an RDP connection via virtual channel to the server PC.
There has to be a logon and the tiles have to be hidden and also the server part of the software hast to be startet.
In order to hide the normal desktop under earlier versions of windows we used the following commands:
// For Windows Vista and Windows 7 hide the Status-Bar and all Desktop-Icons
int a_hWndTaskBar = FindWindow( "Shell_TrayWnd", null );
int a_hWndStart = FindWindow( "Button", "Start" );
int a_hWndDesktop = FindWindow( "Progman", null );
bool a_bResult = false;
try
{
a_bResult = SetWindowPos( a_hWndTaskBar, 0, 0, 0, 0, 0, SWP_HIDEWINDOW );
a_bResult = SetWindowPos( a_hWndStart, 0, 0, 0, 0, 0, SWP_HIDEWINDOW );
a_bResult = ShowWindow( a_hWndDesktop, SW_HIDE );
}
catch( Exception e )
{
MessageBox.Show( e.Message );
}
What do I have to do in order to achieve this with windows 8.1?
Regards
Markus
Here: Works for me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Constants.UI
{
public class Taskbar
{
[DllImport("user32.dll")]// For Windows Mobile, replace user32.dll with coredll.dll
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
[DllImport("user32.dll")]
private static extern int ShowWindow(int hwnd, int command);
private const int SW_HIDE = 0;
private const int SW_SHOW = 1;
protected static int Handle
{
get
{
return HandlePtr.ToInt32();
}
}
protected static IntPtr HandlePtr
{
get
{
return FindWindow("Shell_TrayWnd", "");
}
}
protected static int StartHandle
{
get
{
int hStart = FindWindow("Button", "Start").ToInt32();
if (hStart == 0)
{
hStart = FindWindowEx(HandlePtr, IntPtr.Zero, "Start", null).ToInt32(); //windows 8
}
return hStart;
}
}
private Taskbar()
{
// hide ctor
}
static object lockAccess = new object();
public static void Show()
{
try
{
lock (lockAccess)
{
ShowWindow(Handle, SW_SHOW);
ShowWindow(StartHandle, SW_SHOW);
}
}
catch { }
}
public static void Hide()
{
try
{
lock (lockAccess)
{
ShowWindow(Handle, SW_HIDE);
ShowWindow(StartHandle, SW_HIDE);
}
}
catch { }
}
}

C# LPT inpout32.dll

I don't get any error or exception.
Button in one Window:
private void button1_Click(object sender, EventArgs e)
{
ControlPort.Output(0x378, 0xff);
}
and inpout.dll interface:
class ControlPort
{
[DllImport("inpout32.dll", EntryPoint = "Out32")]
public static extern void Output(int adress, int value);
}
What is wrong?
LED on D2 is on all the time.
I have Windows 7 x64 Ultimate.
For x64 you should use "InpOutx64.dll".
Visit: http://www.highrez.co.uk/Downloads/InpOut32/default.htm
There you can read more and find samples.
Working code if somebody needs it.
using System;
using System.Runtime.InteropServices;
namespace ParallelPort
{
public class PortAccess
{
//inpout.dll
[DllImport("inpout32.dll")]
private static extern UInt32 IsInpOutDriverOpen();
[DllImport("inpout32.dll")]
private static extern void Out32(short PortAddress, short Data);
[DllImport("inpout32.dll")]
private static extern char Inp32(short PortAddress);
[DllImport("inpout32.dll")]
private static extern void DlPortWritePortUshort(short PortAddress, ushort Data);
[DllImport("inpout32.dll")]
private static extern ushort DlPortReadPortUshort(short PortAddress);
[DllImport("inpout32.dll")]
private static extern void DlPortWritePortUlong(int PortAddress, uint Data);
[DllImport("inpout32.dll")]
private static extern uint DlPortReadPortUlong(int PortAddress);
[DllImport("inpoutx64.dll")]
private static extern bool GetPhysLong(ref int PortAddress, ref uint Data);
[DllImport("inpoutx64.dll")]
private static extern bool SetPhysLong(ref int PortAddress, ref uint Data);
//inpoutx64.dll
[DllImport("inpoutx64.dll", EntryPoint = "IsInpOutDriverOpen")]
private static extern UInt32 IsInpOutDriverOpen_x64();
[DllImport("inpoutx64.dll", EntryPoint = "Out32")]
private static extern void Out32_x64(short PortAddress, short Data);
[DllImport("inpoutx64.dll", EntryPoint = "Inp32")]
private static extern char Inp32_x64(short PortAddress);
[DllImport("inpoutx64.dll", EntryPoint = "DlPortWritePortUshort")]
private static extern void DlPortWritePortUshort_x64(short PortAddress, ushort Data);
[DllImport("inpoutx64.dll", EntryPoint = "DlPortReadPortUshort")]
private static extern ushort DlPortReadPortUshort_x64(short PortAddress);
[DllImport("inpoutx64.dll", EntryPoint = "DlPortWritePortUlong")]
private static extern void DlPortWritePortUlong_x64(int PortAddress, uint Data);
[DllImport("inpoutx64.dll", EntryPoint = "DlPortReadPortUlong")]
private static extern uint DlPortReadPortUlong_x64(int PortAddress);
[DllImport("inpoutx64.dll", EntryPoint = "GetPhysLong")]
private static extern bool GetPhysLong_x64(ref int PortAddress, ref uint Data);
[DllImport("inpoutx64.dll", EntryPoint = "SetPhysLong")]
private static extern bool SetPhysLong_x64(ref int PortAddress, ref uint Data);
private bool _X64;
private short _PortAddress;
public PortAccess(short PortAddress)
{
_X64 = false;
_PortAddress = PortAddress;
try
{
uint nResult = 0;
try
{
nResult = IsInpOutDriverOpen();
}
catch (BadImageFormatException)
{
nResult = IsInpOutDriverOpen_x64();
if (nResult != 0)
_X64 = true;
}
if (nResult == 0)
{
throw new ArgumentException("Unable to open InpOut32 driver");
}
}
catch (DllNotFoundException)
{
throw new ArgumentException("Unable to find InpOut32.dll");
}
}
//Public Methods
public void Write(short Data)
{
if (_X64)
{
Out32_x64(_PortAddress, Data);
}
else
{
Out32(_PortAddress, Data);
}
}
public byte Read()
{
if (_X64)
{
return (byte)Inp32_x64(_PortAddress);
}
else
{
return (byte)Inp32(_PortAddress);
}
}
}
}
You are not going to get an exception when you get this wrong, at most a blue screen. Pick one of:
you are using the wrong address (0x3bc, 0x2f8)
you wired the LED wrong
you broke into the wrong museum to get the hardware
The question is too poorly documented to help you beyond this.
I resolved a problem with LPT port on Windows 2000 on my old laptop, where the data port (pin2-pin9) could not be set.
Using this imported function:
[DllImport("inpout32.dll", EntryPoint = "Out32")]
public static extern void Out32(int address, int value);
after every reboot or restart of Windows I have to call this line:
Out32(0x378 + 2, 0x00);
so that the port works properly. I think the problem is in the bi-directional settings (control port at 6th bit on 0x37A).

How can I tell which application of openoffice is running?

I want to look in the list of processes to determine if OpenOffice Calc is running or if OpenOffice Writer is running. With QuickStart off, I get a scalc.exe and an swriter.exe so its simple.
However when the quick start is on I just get soffice.bin and soffice.exe
Is there a way of asking those processes which application is running?
I think there is no way around checking the window title. You would have to enumerate all windows and check whether the title ends with "- OpenOffice.org Writer" or "- OpenOffice.org Calc" etc.
The following short sample would check whether Writer is running:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace Sample
{
public class Window
{
public string Title { get; set; }
public int Handle { get; set; }
public string ProcessName { get; set; }
}
public class WindowHelper
{
/// <summary>
/// Win32 API Imports
/// </summary>
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder title, int size);
[DllImport("user32.dll")]
private static extern int EnumWindows(EnumWindowsProc ewp, int lParam);
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
public delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
private List<Window> _openOfficeWindows;
public List<Window> GetOpenOfficeWindows()
{
_openOfficeWindows = new List<Window>();
EnumWindowsProc ewp = new EnumWindowsProc(EvalWindow);
EnumWindows(ewp, 0);
return _openOfficeWindows;
}
private bool EvalWindow(IntPtr hWnd, int lParam)
{
if (!IsWindowVisible(hWnd))
return (true);
uint lpdwProcessId;
StringBuilder title = new StringBuilder(256);
GetWindowThreadProcessId(hWnd, out lpdwProcessId);
GetWindowText(hWnd, title, 256);
Process p = Process.GetProcessById((int)lpdwProcessId);
if (p != null && p.ProcessName.ToLower().Contains("soffice"))
{
_openOfficeWindows.Add(new Window() { Title = title.ToString(), Handle = hWnd.ToInt32(), ProcessName = p.ProcessName });
}
return (true);
}
}
class Program
{
static void Main(string[] args)
{
WindowHelper helper = new WindowHelper();
List<Window> openOfficeWindows = helper.GetOpenOfficeWindows();
foreach (var item in openOfficeWindows)
{
if (item.Title.EndsWith("- OpenOffice.org Writer"))
{
Console.WriteLine("Writer is running");
}
}
}
}
}

Categories

Resources