adjust phone volume - Windows Mobile Development and Hacking General

Is there a way using C# and PInvoke to adjust the phone volume programatically, high, medium, low and vibrate?

Anybody at all? Even c++ code would be fine.

BTT.
anyone able to do this yet?

Climber104 said:
Is there a way using C# and PInvoke to adjust the phone volume programatically, high, medium, low and vibrate?
Click to expand...
Click to collapse
I haven't figure out the "vibrate only" settings yet, but here is what I have
public enum Ringer : int
{
VERY_HIGH = -1,
HIGH = -858993459,
MEDIUM = -1717986918,
NORMAL = 1717986918,
LOW = 858993459,
OFF = 0
}
private void _setRinger(int value)
{
RingerRegistry ringerReg = new RingerRegistry();
ringerReg.setVolume(value);
}
public class RingerRegistry
{
//HKCU\ControlPanel\SoundCategories\Ring\InitVol
private string Key = "InitVol";
private static string SoundKey = @"ControlPanel\SoundCategories\Ring";
private static string SoundKey2 = @"ControlPanel\SoundCategories\RingPreview";
private RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(SoundKey);
private RegistryKey registryKey2 = Registry.CurrentUser.CreateSubKey(SoundKey2);
public void setVolume(int volume)
{
string A = registryKey.GetValue(Key).ToString();
string B = registryKey2.GetValue(Key).ToString();
registryKey.SetValue(Key, volume);
registryKey.Flush();
registryKey2.SetValue(Key, volume);
registryKey2.Flush();
string C = registryKey.GetValue(Key).ToString();
string D = registryKey2.GetValue(Key).ToString();
registryKey2.Close();
registryKey.Close();
}
public int getVolume()
{
return (Convert.ToInt32(registryKey.GetValue(SoundKey + "InitVol", "0")));
}
}

You could use the coredll file to adjust the volume. This is how I do it in VB:
<DllImport("COREDLL")> _
Public Shared Function waveOutSetVolume(ByVal hMod As IntPtr, ByVal lVolume As Integer) As Integer
End Function
Then I use the function:
waveOutSetVolume(IntPtr.Zero, volume)
Volume is an integer ranging from 0 - 65000.
0 = Min or OFF
65000 = Full
Hope this helps,
Chad.

Related

Programmatically cycle sound icon (sound/vibrate/mute)

When you click on the sound icon, you get the two sliders and three radio buttons. Anyone know how to set those radio buttons through code (C++) so it gets reflected in the icon display (and actually changes the "profile")?. I'd like to change to vibrate/mute/sound at different times using something like alarmToday to run a small app.
Thanks,
sbl
I wrote a profiles app in .net and C++ here are some code snippets;
You can change the registry values for the volumes (I cant remember which as I wrote it a long time ago), then you need to call the following to have the values applied.
// ProfilesHelper.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "ProfilesHelper.h"
#include <windows.h>
#include <Soundfile.h>
void WINEXPORT SetSoundMode(int mode)
{
// Initialize an empty SNDFILEINFO structure
SNDFILEINFO sndfile = {0};
if (mode == 0)
sndfile.sstType = SND_SOUNDTYPE_ON;
if (mode == 1)
sndfile.sstType = SND_SOUNDTYPE_VIBRATE;
if (mode == 2)
sndfile.sstType = SND_SOUNDTYPE_NONE;
SndSetSound(SND_EVENT_ALL, &sndfile, false);
void AudioUpdateFromRegistry();
}
void WINEXPORT SetSystemVolume(long volume)
{
waveOutSetVolume(NULL, volume);
void AudioUpdateFromRegistry();
}
Hi,
I have a similar need of programatically cycling the sound icon to MUTE VIBRATE and normal volume icon. I can do it successfully on Windows Mobile 5.0. I created a sample application with Visual Studio 2005 for WM 5.0 and I am able to set the icons as i want. But when i tried it for PPC2003 I was not able to compile that. Missing SoudFile.h. Can any one help me to find out how to do the same thing on PPC2003 specifically i-mate devices like PDA2 and PDA2K.
Thanks
With Regards,
Bhagat Nirav K.
i know its a 2 ur old post..but i need help also now
how can i mute sounds using C# in .net 2.0 for WM6
Just forget about this header file...
Operate on HKCU\ControlPanel\Notifications\ShellOverrides\Mode value. It can have 3 states: 0 == normal, 1 == vibrate and 2 == silent. That's all
Probably you need to call AudioUpdateFromRegistry function from coredll.dll.
Or... another method
look at HKCU\ControlPanel\Sounds\RingTone0:Sound, it takes 3 different values:
*none*
*vibrate*
your ringtone name, taken from SavedSound value in the same key.
Hi,
Firstly I know this post is way old, but I thought of responding to it since I was stuck on this topic for a couple of days and couldnt find a way to resolve it.
Also others having this problem will also be redirected here through various search results as I was. So to aid them
1. Meddling with the registry to change the sound profiles didnt work for me. I tried Changing the Mode inHKCU\ControlPanel\Notifications\ShellOverrides\Mode but that didnt work on my phone.
2. What I currently have working is the following code - C# with Pinvoke
public enum SND_SOUNDTYPE
{
On,
File,
Vibrate,
None
}
private enum SND_EVENT
{
All,
RingLine1,
RingLine2,
KnownCallerLine1,
RoamingLine1,
RingVoip
}
[StructLayout(LayoutKind.Sequential)]
private struct SNDFILEINFO
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szPathName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
public SND_SOUNDTYPE sstType;
}
[DllImport("coredll.dll")]
public static extern void AudioUpdateFromRegistry ();
[DllImport("aygshell.dll", SetLastError = true)]
private static extern uint SndSetSound(SND_EVENT seSoundEvent, ref SNDFILEINFO pSoundFileInfo, bool fSuppressUI);
static void SetProfileNormal()
{
SNDFILEINFO soundFileInfo = new SNDFILEINFO();
soundFileInfo.sstType = SND_SOUNDTYPE.On;
uint num = SndSetSound(SND_EVENT.All, ref soundFileInfo, true);
AudioUpdateFromRegistry();
}
static void SetProfileVibrate()
{
SNDFILEINFO soundFileInfo = new SNDFILEINFO();
soundFileInfo.sstType = SND_SOUNDTYPE.Vibrate;
uint num = SndSetSound(SND_EVENT.All, ref soundFileInfo, true);
AudioUpdateFromRegistry();
}
static void SetProfileMuted()
{
SNDFILEINFO soundFileInfo = new SNDFILEINFO();
soundFileInfo.sstType = SND_SOUNDTYPE.None;
uint num = SndSetSound(SND_EVENT.All, ref soundFileInfo, true);
AudioUpdateFromRegistry();
}
Hope this helps

[WM6] Disabling taskbar, SIP and hardware keys (including green and red buttons)

Hello there!
I've seen a lot of questions on this topic, and just yesterday, my client asked for this feature implemented in the app that we are currently developing...
After a veeeery intensive and long night, i finally found how to disable all these things! The code is written in c# using .net CF 2.0, and has been tested successfully on a HTC Tynt device. The interesting thing is that it will also disable the End Call and Make Call hardware buttons (VK_TEND and VK_TTALK). If you intend to use this in a production environment you might consider improoving it a little bit.
[DllImport("coredll.dll")]
private static extern bool UnregisterFunc1(KeyModifiers modifiers, int keyID);
[DllImport("coredll.dll", SetLastError = true)]
public static extern bool RegisterHotKey(IntPtr hWnd, // handle to window
int id, // hot key identifier
KeyModifiers Modifiers, // key-modifier options
int key //virtual-key code
);
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8,
Modkeyup = 0x1000,
}
private void DeactivateUI()
{
try
{
// deactivate the SIP button
IntPtr hSip = FindWindow("MS_SIPBUTTON", "MS_SIPBUTTON");
EnableWindow(hSip, false);
// deactivate the SIP button
IntPtr hTaskBar = FindWindow("HHTaskBar", null);
EnableWindow(hTaskBar, false);
// deactivate the hardware keys
for (Int32 iCounter = 193; iCounter <= 207; iCounter++)
{
UnregisterFunc1(KeyModifiers.Windows, iCounter);
RegisterHotKey(this.Handle, iCounter, KeyModifiers.Windows, iCounter);
}
UnregisterFunc1(KeyModifiers.None, 0x73); //VK_TEND
RegisterHotKey(this.Handle, 0x73, KeyModifiers.None, 0x73);
UnregisterFunc1(KeyModifiers.None, 0x72);
RegisterHotKey(this.Handle, 0x72, KeyModifiers.None, 0x72); //VK_TTALK
}
catch (Exception ex)
{
Log.WriteError(ex, false);
}
}
Cheers!
Very good, helped me a lot! But how do I unlock the keys again, without rebooting?
Thanks!
gciochina said:
Hello there!
I've seen a lot of questions on this topic, and just yesterday, my client asked for this feature implemented in the app that we are currently developing...
After a veeeery intensive and long night, i finally found how to disable all these things! The code is written in c# using .net CF 2.0, and has been tested successfully on a HTC Tynt device. The interesting thing is that it will also disable the End Call and Make Call hardware buttons (VK_TEND and VK_TTALK). If you intend to use this in a production environment you might consider improoving it a little bit.
[DllImport("coredll.dll")]
private static extern bool UnregisterFunc1(KeyModifiers modifiers, int keyID);
[DllImport("coredll.dll", SetLastError = true)]
public static extern bool RegisterHotKey(IntPtr hWnd, // handle to window
int id, // hot key identifier
KeyModifiers Modifiers, // key-modifier options
int key //virtual-key code
);
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8,
Modkeyup = 0x1000,
}
private void DeactivateUI()
{
try
{
// deactivate the SIP button
IntPtr hSip = FindWindow("MS_SIPBUTTON", "MS_SIPBUTTON");
EnableWindow(hSip, false);
// deactivate the SIP button
IntPtr hTaskBar = FindWindow("HHTaskBar", null);
EnableWindow(hTaskBar, false);
// deactivate the hardware keys
for (Int32 iCounter = 193; iCounter <= 207; iCounter++)
{
UnregisterFunc1(KeyModifiers.Windows, iCounter);
RegisterHotKey(this.Handle, iCounter, KeyModifiers.Windows, iCounter);
}
UnregisterFunc1(KeyModifiers.None, 0x73); //VK_TEND
RegisterHotKey(this.Handle, 0x73, KeyModifiers.None, 0x73);
UnregisterFunc1(KeyModifiers.None, 0x72);
RegisterHotKey(this.Handle, 0x72, KeyModifiers.None, 0x72); //VK_TTALK
}
catch (Exception ex)
{
Log.WriteError(ex, false);
}
}
Cheers!
Click to expand...
Click to collapse
Can u provide the EnableWindow method.I am getting the error in this method
Implement code
Hello!
I have created app to WM 5 - 6.5, but users can close it using END button. I see your code, but i can't implement ( i mean I don't have sufficient knowledge) it to visual studio 2008.
Could you tell me what should I do?
Error 1 'APP.Kiosk' does not contain a definition for 'Handle' and no extension method 'Handle' accepting a first argument of type 'APP.Kiosk' could be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\lupag\Moje dokumenty\Pobieranie\CEKiosk\CEKiosk\Kiosk.cs 155 43 CEKiosk
Handle? wtf

[Q] Parse Bluetooth received string

Hi, I have a newbie question..
I have modified the bluetoothChat example to get serial data from my pc to my phone over bluetooth.
The code uses the following code to keep listening for incoming data:
Code:
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes = 0;
// byte x = 0;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
BluetoothChatService.this.start();
break;
}
}
}
And in the MainActivity the following code when data is received:
Code:
case MESSAGE_READ:
byte [] readBuf;
//readBuf = (byte[]) msg.obj;
readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1); // create string from bytes array
messageString = messageString + readMessage;
if (messageString.length()<10){
TextView text = (TextView) findViewById(R.id.textView1); // Display output
text.setText("<10....");
break;
}
sb.append(readMessage); // append string
int endOfLineIndex = sb.indexOf("#"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
TextView text = (TextView) findViewById(R.id.textView1); // Display output
text.setText(sbprint);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
}
break;
As shown i have added a endOfLineIndex loop to find the end of the received string and show the received string in a textfield. The problem with my code is when sending a string like "0123456789#" the shown text in the textView1 is mostly not the send string.. I get strings like 0123,4560123456789, etc.. Somehow there is still data in the buffer i quess.
Is there a way to clear or ignore the received data and only parse the wanted string form the buffer? If this is possible i can add a start identifier to the string..
The main goal is too parse a string like: #150,000,001,000,0.0,-0.1,40.3,144.0,001,OKE where each value is a variable which needed to be placed in a textview.
Thanks for any suggestions!
Kind regards,
Bas
This one "0123456789#" should return "0123456789". Does it?
You invoke substring().
Quote from the docs:
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Click to expand...
Click to collapse
(http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring(int, int))
That means that the last character (the #) is missed out.
Thanks Nikwen,
I do miss out the end off string character #. The problem is i get different strings out of the buffer... If i send 0123456789# with a one second interval i get different results.. sometimes i get the string like expected which is 0123456789. but most of the time i get results like 0123, 456789,12,1,etc etc. it looks like the buffer is not cleared or something

More secure encryption class using salt

Continuing with the theme from my last thread where I posted a simple class for encrypting strings using the SHA-512 hashing algorithm, here is an improved version that generates a random 20 byte salt to add in with the string to be hashed. This is then hashed providing greater security.
Due to the random generation of the salt each time a string is hashed, this makes it pretty much impossible to get the same hash for a string, therefore once the salt has been generated the first time round it is stored in sharedPreferences for future uses so that you can use it for checking matches etc
Method of converting the bytes to hex string adapted from maybeWeCouldStealAVan's method @ stackoverflow.
Code:
public class Crypto {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
protected static String SHA512(String string, Context context) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
String salt = getSalt(context);
md.update(salt.getBytes());
byte[] bytes = md.digest(string.getBytes());
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static String getSalt(Context context) throws NoSuchAlgorithmException {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String salt = preferences.getString("salt", null);
if (salt == null) {
byte[] saltBytes = new byte[20];
SecureRandom.getInstance("SHA1PRNG").nextBytes(saltBytes);
salt = new String(saltBytes);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("salt", salt).commit();
}
return salt;
}
}
Usage:
Code:
String example = "example";
try {
example = Crypto.SHA512(example, context);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Thanks for sharing, it's quite usefull ! I will include it to my project
Jonny said:
Continuing with the theme from my last thread where I posted a simple class for encrypting strings using the SHA-512 hashing algorithm, here is an improved version that generates a random 20 byte salt to add in with the string to be hashed. This is then hashed providing greater security.
Due to the random generation of the salt each time a string is hashed, this makes it pretty much impossible to get the same hash for a string, therefore once the salt has been generated the first time round it is stored in sharedPreferences for future uses so that you can use it for checking matches etc
Method of converting the bytes to hex string adapted from maybeWeCouldStealAVan's method @ stackoverflow.
Code:
public class Crypto {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
protected static String SHA512(String string, Context context) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
String salt = getSalt(context);
md.update(salt.getBytes());
byte[] bytes = md.digest(string.getBytes());
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static String getSalt(Context context) throws NoSuchAlgorithmException {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String salt = preferences.getString("salt", null);
if (salt == null) {
byte[] saltBytes = new byte[20];
SecureRandom.getInstance("SHA1PRNG").nextBytes(saltBytes);
salt = new String(saltBytes);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("salt", salt).commit();
}
return salt;
}
}
Usage:
Code:
String example = "example";
try {
example = Crypto.SHA512(example, context);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Click to expand...
Click to collapse
Thanks
Gesendet von meinem LG-D855 mit Tapatalk

[Q] App crashes when editText is left blank. How do I fix it?

I'm making an app for a friends gym that has a BMI and BMR calculator. It works but if any editText field is left blanc the app crashes.
It crashes once I press the "male" button...
Code:
View rootView = inflater.inflate(R.layout.fragment_bmr, container, false);
//step2 : get all the views from xml file.
feet = (EditText) rootView.findViewById(R.id.feet);
inch = (EditText) rootView.findViewById(R.id.inch);
weight = (EditText) rootView.findViewById(R.id.weight2);
age = (EditText) rootView.findViewById(R.id.age2);
bmr = (TextView) rootView.findViewById(R.id.editText3);
male = (Button) rootView.findViewById(R.id.male);
b2 = (Button) rootView.findViewById(R.id.female);
//step3 : write add functionality.
male.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String f = feet.getText().toString();
int feet = Integer.parseInt(f);
String i = inch.getText().toString();
int inch = Integer.parseInt(i);
String w = weight.getText().toString();
int weight = Integer.parseInt(w);
String a = age.getText().toString();
int age = Integer.parseInt(a);
double result = 66+(6.23*weight)+(12.7*(feet*12+inch))-(6.8*age);
result = Math.round(result*10.0)/10.0;
String res = String.valueOf(result);
bmr.setText(res);
}
});
I don't post code on here much so if did it wrong I'd appreciate if someone corrects me
Sent from my Nexus 6 using XDA Free mobile app
jeb192004 said:
I'm making an app for a friends gym that has a BMI and BMR calculator. It works but if any editText field is left blanc the app crashes.
It crashes once I press the "male" button...
Code:
View rootView = inflater.inflate(R.layout.fragment_bmr, container, false);
//step2 : get all the views from xml file.
feet = (EditText) rootView.findViewById(R.id.feet);
inch = (EditText) rootView.findViewById(R.id.inch);
weight = (EditText) rootView.findViewById(R.id.weight2);
age = (EditText) rootView.findViewById(R.id.age2);
bmr = (TextView) rootView.findViewById(R.id.editText3);
male = (Button) rootView.findViewById(R.id.male);
b2 = (Button) rootView.findViewById(R.id.female);
//step3 : write add functionality.
male.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String f = feet.getText().toString();
int feet = Integer.parseInt(f);
String i = inch.getText().toString();
int inch = Integer.parseInt(i);
String w = weight.getText().toString();
int weight = Integer.parseInt(w);
String a = age.getText().toString();
int age = Integer.parseInt(a);
double result = 66+(6.23*weight)+(12.7*(feet*12+inch))-(6.8*age);
result = Math.round(result*10.0)/10.0;
String res = String.valueOf(result);
bmr.setText(res);
}
});
I don't post code on here much so if did it wrong I'd appreciate if someone corrects me
Sent from my Nexus 6 using XDA Free mobile app
Click to expand...
Click to collapse
I'm guessing its because you can't parseInt on an empty string (or one that's not an integer). You need to run an assert on your strings to make sure its not null.
Sorry empty string is not null. There will be parseInt error on string and not null pointer exception.
@jeb192004
Check if input string is numeric then do parseInt.
Note:
This answer was not to Jonny.
Sent from my XT1033 using XDA Free mobile app
I did this:
Code:
male.setOnClickListener(new OnClickListener() { [user=439709]@override[/user]
public void onClick(View v) {
String f = feet.getText().toString();
String i = inch.getText().toString();
String w = weight.getText().toString();
String a = age.getText().toString();
if(feet.getText().toString().equals("") ){
feet.setError("Please Fill Out Your Height");}
else if(inch.getText().toString().equals("") ){
inch.setError("Please Fill Out Your Height");}
else if(weight.getText().toString().equals("") ){
weight.setError("Please Fill Out Your weight");}
else if( age.getText().toString().equals(""))
{
age.setError("Please Fill Out Your Age");
}
else{
int feet = Integer.parseInt(f);
int inch = Integer.parseInt(i);
int weight = Integer.parseInt(w);
int age = Integer.parseInt(a);
double result = 66+(6.23*weight)+(12.7*(feet*12+inch))-(6.8*age);
result = Math.round(result*10.0)/10.0;
String res = String.valueOf(result);
bmr.setText(res);
}
}
});
[\CODE]
I did this a different way at first, using "||" between each if/else if statement instead of the if/else if between each one and it worked except for my "inch" edittext. That one still made the app crash. Doing it the way I have shown works but my error message doesn't always show up. Sometimes I have to click the edit text field for it to show up. The red dot does show up in the text field every time tho.
It took a bit of searching to figure out what you guys were talking about and how to get it to work. I'm really new to this and learning as I go. Doing this more as a hobby...
Sent from my Nexus 6 using XDA Free mobile app
I surround mine with a try/catch. Then if the edittext is blank, I prompt the user with a toast to input something, even a zero. Might not be the best way, but hey, I'm a F'n noob....

Categories

Resources