⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Enabling Vibration in Windows Mobile on C#

Archive - may be useful to someone
Most modern phone models support the vibration alert function, so it can be used (for example, in games when explosions occur to add more realism, or when writing communication programs, to notify the user of incoming messages while the device is in a pocket).
 

Here I will provide three methods of implementing vibration on Windows Mobile devices in the .NET CF environment. Although, to be honest, all of them are implemented through the use of API, so they can be used not only in .NET.

So, example #1 (which did not work for me personally, I assume it should work on Windows Mobile 5.X - I don't have a device to test it on)

//Инициирует виброзвонок.
//И сообщает об успехе либо возвращает ошибку.
[DllImport("aygshell.dll")]
private static extern int Vibrate(
            int cvn,
            IntPtr rgvn,
            uint fRepeat,
            uint dwTimeout);

//Останавливает виброзвонок.
//И сообщает об остановке либо об ошибке.
[DllImport("aygshell.dll")]
private static extern int VibrateStop();
        

//Проверяет возможность использования виброзвонка.
[DllImport("aygshell.dll")]
private static extern int VibrateGetDeviceCaps(VibrationCapabilities caps);


//Перечисление используется функцией VibrateGetDeviceCaps для
//определения возможности воспроизведения виброзвонка.
public enum VibrationCapabilities : int
        {
            VDC_Amplitude,
            VDC_Frequency
        }

//Включаем вибратор
public static bool BeginVibrate()
        {
            int result = Vibrate(0, IntPtr.Zero, uint.MaxValue, uint.MaxValue);
            MessageBox.Show(result.ToString());
            if (result != 0)
            { return false; }
            return true;
        }

//Выключае вибратор
public static bool EndVibrate()
        {
            int result = VibrateStop();
            if (result != 0)
            { return false; }
            return true;
        }

This (first) example did not work for me, but it is often cited in other sources, so it should work.


Example #2 (the simplest)

//Метод простой для Windows Mobile 6.X
//Этим методом издаёт - длинный бзздынь и замолкает.
[DllImport("aygshell.dll", SetLastError = true)]
private static extern uint SndPlaySync(String pszSoundFile, int dwFlags);

//Включаем вибрацию для WinMobile 6.X Метод №1
SndPlaySync("*vibrate*", 0);

Example #3 (the most complex - but the most effective, using indicators)

//Метод через индикаторы для 6.X
struct NLED_SETTINGS_INFO
        {
            public uint LedNum;
            public int OffOnBlink;
            public long TotalCycleTime;
            public long OnTime;
            public long OffTime;
            public int MetaCycleOn;
            public int MetaCycleOff;
        };

private const uint NLED_SETTINGS_INFO_ID = 2;

[DllImport("coredll.dll", SetLastError = true)]
private static extern bool NLedSetDevice(uint DeviceInput, ref NLED_SETTINGS_INFO pInput);

// Включаем вибро. Указать номер канала! У каждого устройства он свой
void LedStart(uint id)
        {
            NLED_SETTINGS_INFO settings = new NLED_SETTINGS_INFO();
            settings.LedNum = id;
            settings.OffOnBlink = 1;
            NLedSetDevice(NLED_SETTINGS_INFO_ID, ref settings);
        }

// Выключаем вибро
void LedStop(uint id)
        {
            NLED_SETTINGS_INFO settings = new NLED_SETTINGS_INFO();
            settings.LedNum = id;
            settings.OffOnBlink = 0;
            NLedSetDevice(NLED_SETTINGS_INFO_ID, ref settings);
        }

//Включаем индикатор, ждем onTime миллисекунд, выключаем и ждем offTime миллисекунд.
//Повторяем цикл указанное count количество раз.
void VibrateByLed(uint LeadNum, int onTime, int offTime, int count)
        {
            for (int i = 0; i < count; i++)
            {
                LedStart(LeadNum);
                System.Threading.Thread.Sleep(onTime);
                LedStop(LeadNum);
                System.Threading.Thread.Sleep(offTime);
            }
        }


......

// 1 - номер индикатора для "вибро" на моем устройстве.
VibrateByLed(1, 100, 150, 5); // лучше стартовать в отдельном потоке.

That's it.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.