Silence detection in Kinect V2 - kinect

I am using winmm.dll to record audio from kinect using below method :
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
private static extern int record(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
For now, I am using Stop button click to stops the recording but I want to stop Recording while detecting silence for sometimes.Because I want to remove "StopRecording" button and Stops the recording if the user doesn't speak for 10 seconds.

Related

mouse_event vs real mouse event ( gameing bot )

background :
I wrote a bot to play poker in pokerstars.com. Since 2022 09 14 , the simulation for mouse-move and mouse-click is not working any more.
code:
I used below c# statement to make a click.
enum MouseEventFlag : uint
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004
}
declaration
[DllImport("user32.dll", EntryPoint = "mouse_event")]
static extern void mouse_event(MouseEventFlag dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
call
mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.LeftUp, 0, 0, 0, 0);
current situation :
when I need to play a CHECK action, I used to click the CHECK
BUTTON / or it is simulated by my program-bot with mouse_event()
called.
now : the simulation do not work, it looks like ANY PROGRAMMED actions is EATTEN by the pokerstar application. but I can still
click the CHECK BUTTON manually.
I did a search about topics in stackoverflow, experts saying there is NO DIFFERENCE between the manual/simulation click.
any hint to solved this? thanks

Window management in C#

I am using selenium c# for web automation and I am having a problem arranging windows. See attached image of what am trying to achieve.
After a While, I found a workaround.
Every time a window is opened I get its handle by
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetForegroundWindow();
and store it.
I get the size of the screen by:
int h = (int)Screen.PrimaryScreen.Bounds.Height;
int w = (int)Screen.PrimaryScreen.Bounds.Width;
I divide the screen and arrange the windows as needed using the function:
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
Results

SetWindowLong & SetLayeredWindowAttributes doesnt work on different user C#

The goal is
I want to change the opacity of some application (target) running on win xp.
The situation
I logged in win xp as AD (active dir) user account (some-domain\username)
most of the target applications are run as local user or another ad user
The problem and my Question
SetWindowLong & SetLayeredWindowAttributes doesn't work on target application that run as other user account. But it works on target application that runs under the same user account (logged user account)
How to change other app's window opacity that run as different user account?
Illustration app
It's a win form app (let's call it OpaciToggler.exe). I have 2 buttons (btnRunSomething and btnHideThatThing) and a textbox (txtPid). As simple as that.
When I click the btnRunSomething, it run an .exe as different user. All the details is in the app.config. In this case I run this application (OpaciToggler.exe, from the debug/bin) as different user (localComputer\user1)
The txtPid is for manual pid input. Usually I open the task manager (win > run > taskmgr) and find the pid (under the process tab) of any application (target) I want to test with, then type it here.
When I click the btnHideThatThing, it'll toggle the opacity of the target application (whose pid in the txtPid)
Code C#
This is how I call the target app.
private void btnRunSomething_Click(object sender, EventArgs e)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.Domain = ConfigurationManager.AppSettings["StartInfoDomain"];
p.StartInfo.UserName = ConfigurationManager.AppSettings["StartInfoUserName"];
p.StartInfo.FileName = ConfigurationManager.AppSettings["StartInfoFileName"];
p.StartInfo.Arguments = ConfigurationManager.AppSettings["StartInfoArguments"];
System.String rawPassword = ConfigurationManager.AppSettings["StartInfoPassword"];
System.Security.SecureString encPassword = new System.Security.SecureString();
foreach (System.Char c in rawPassword)
{
encPassword.AppendChar(c);
}
p.StartInfo.Password = encPassword;
p.StartInfo.UseShellExecute = false;
p.Start();
}
This is how I try to call the opacity thing
private void btnHideThatThing_Click(object sender, EventArgs e)
{
// manual input pid
int pid = int.Parse(txtPid.Text);
IntPtr mwh = Process.GetProcessById(pid).MainWindowHandle;
doHideThing(mwh);
// doHideThing(Process.GetProcessById(int.Parse(txtPid.Text)).MainWindowHandle);
}
The hide method
private void doHideThing(IntPtr hndl)
{
SetWindowLong(hndl, GWL_EXSTYLE, GetWindowLong(hndl, GWL_EXSTYLE) ^ WS_EX_LAYERED).ToString();
// _whatNow = Marshal.GetLastWin32Error();
SetLayeredWindowAttributes(hndl, 0, (255 * 20) / 100, LWA_ALPHA).ToString();
// _whatNow = Marshal.GetLastWin32Error();
RedrawWindow(hndl, IntPtr.Zero, IntPtr.Zero,
RedrawWindowFlags.Erase | RedrawWindowFlags.Invalidate |
RedrawWindowFlags.Frame | RedrawWindowFlags.AllChildren);
}
other codes
private const int GWL_EXSTYLE = -20;
private const int GWL_STYLE = -16;
private const int WS_EX_LAYERED = 0x80000;
private const int LWA_ALPHA = 0x2;
private const int LWA_COLORKEY = 0x1;
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprcUpdate, IntPtr hrgnUpdate, RedrawWindowFlags flags);
RedrawWindowFlags enum (I don't remember where I get this)
[Flags()]
enum RedrawWindowFlags : uint
{
/// <summary>
/// Invalidates the rectangle or region that you specify in lprcUpdate or hrgnUpdate.
/// You can set only one of these parameters to a non-NULL value. If both are NULL, RDW_INVALIDATE invalidates the entire window.
/// </summary>
Invalidate = 0x1,
/// <summary>Causes the OS to post a WM_PAINT message to the window regardless of whether a portion of the window is invalid.</summary>
InternalPaint = 0x2,
/// <summary>
/// Causes the window to receive a WM_ERASEBKGND message when the window is repainted.
/// Specify this value in combination with the RDW_INVALIDATE value; otherwise, RDW_ERASE has no effect.
/// </summary>
Erase = 0x4,
/// <summary>
/// Validates the rectangle or region that you specify in lprcUpdate or hrgnUpdate.
/// You can set only one of these parameters to a non-NULL value. If both are NULL, RDW_VALIDATE validates the entire window.
/// This value does not affect internal WM_PAINT messages.
/// </summary>
Validate = 0x8,
NoInternalPaint = 0x10,
/// <summary>Suppresses any pending WM_ERASEBKGND messages.</summary>
NoErase = 0x20,
/// <summary>Excludes child windows, if any, from the repainting operation.</summary>
NoChildren = 0x40,
/// <summary>Includes child windows, if any, in the repainting operation.</summary>
AllChildren = 0x80,
/// <summary>Causes the affected windows, which you specify by setting the RDW_ALLCHILDREN and RDW_NOCHILDREN values, to receive WM_ERASEBKGND and WM_PAINT messages before the RedrawWindow returns, if necessary.</summary>
UpdateNow = 0x100,
/// <summary>
/// Causes the affected windows, which you specify by setting the RDW_ALLCHILDREN and RDW_NOCHILDREN values, to receive WM_ERASEBKGND messages before RedrawWindow returns, if necessary.
/// The affected windows receive WM_PAINT messages at the ordinary time.
/// </summary>
EraseNow = 0x200,
Frame = 0x400,
NoFrame = 0x800
}
Example, Test and Test Result
logged in win xp as domainA\ad_user1
run the OpaciToggler.exe application (Instance1, run as domainA\ad_user1)
Then I click the run something. It opens another OpaciToggler.exe (Instance2), runs as another user account (run as localcomputer\l_user1) OR right click the .exe then click run as..
Instance1
pid: 1234
run as: domainA\ad_user1
txtPid: 5678 (Instance2, doesn't work)
txtPid: 1234 (self, works)
txtPid: any pid run as the same account (ex: notepad.exe, calc.exe, etc, works)
Instance2
pid: 5678
run as: localcomputer\l_user1
txtPid: 1234 (Instance 1, doesnt work)
txtPid: 5678 (self, works)
txtPid: any pid run as the same account (localcomputer\l_user1) (ex: notepad.exe, calc.exe, etc, doesn't work!!)
Again, my Question
How to change other app's window opacity that run as different user account?
Thanks and sorry for my bad English :(.

.NET CF - MSMQ ActivateDevice() Crash

I have a .NET 3.5 Compact Framework application that uses MSMQ.
We are running this application on an Intermec CN3, Windows Mobile 5.0 device.
However, when our application first tries to active the MSMQ service with ActivateDevice (pinvoke), the application crashes and we get the error report message:
A problem has occuurred with myApp.exe
Please tell Microsoft about this problem, at not cost to you. ect..
What we have done is this:
Hard Reset the Device
Install NETCFv35.wm.armv4i.cab
Install msmq.arm.CAB
*Run a CF console app that sets up MSMQ and the registry
Soft reset the PDA
*Run our application which calls ActivateDevice() on startup
After doing a soft reset, the first time that ActivateDevice() is called, the application crashes.
However, now that we have called ActivateDevice(), MSMQ services are working on the device atleast until it is soft reset again.
Also, any calls to ActivateDevice() will not crash the application.
The console app that we run after a hard reset is basically this:
class InstallRegister
{
public void Main()
{
RunMsmqAdmin("install");
RunMsmqAdmin("register install");
RunMsmqAdmin("register");
SetQuotaValueRegistry("MachineQuota");
SetQuotaValueRegistry("DefaultLocalQuota");
SetQuotaValueRegistry("DefaultQuota");
RunMsmqAdmin("enable binary");
RunMsmqAdmin("enable srmp");
RunMsmqAdmin("start");
RegFlushKey(0x80000002);
}
private void SetQuotaValueRegistry(string quotaValueName)
{
Microsoft.Win32.Registry.SetValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSMQ\\SimpleClient\\"
, quotaValueName
, 100000);
}
private void RunMsmqAdmin(string command)
{
using (Process _process = new Process())
{
_process.StartInfo.FileName = #"\windows\msmqadm.exe";
_process.StartInfo.Arguments = command;
_process.StartInfo.UseShellExecute = true;
_process.Start();
_process.WaitForExit();
}
}
[System.Runtime.InteropServices.DllImport("CoreDll.dll", EntryPoint = "RegFlushKey", SetLastError = true)]
private static extern uint RegFlushKey(uint hKey);
}
Our applications call to ActivateDevice() is basically this:
class ActivateMSMQ
{
public void Active()
{
var handle = ActivateDevice("Drivers\\BuiltIn\\MSMQD", 0);
CloseHandle(handle);
}
[System.Runtime.InteropServices.DllImport("CoreDll.dll", SetLastError = true)]
private static extern IntPtr ActivateDevice(string lpszDevKey, Int32 dwClientInfo);
[System.Runtime.InteropServices.DllImport("CoreDll.dll", SetLastError = true)]
private extern static Int32 CloseHandle(IntPtr hProcess);
}
ActivateDevice() still causes our app the crash whenever the device is soft reset.
Has anyone else experienced this with MSMQ on the compact framework?
Yes this problem occurs. the quick and easy fix for this is to put the code into a separate executable, then on the start of you app launch this process and wait for completion. The process will terminate due to the crash but will return with your calling app still intact. Then just make sure the executable is deployed in your cab so you app can call it.

Send raw ZPL to Zebra printer via USB

Typically, when I plug in my Zebra LP 2844-Z to the USB port, the computer sees it as a printer and I can print to it from notepad like any other generic printer. However, my application has some bar code features. My application parses some input and generates an in-memory string of ZPL. How would I send this ZPL data to my USB device?
I found the answer... or at least, the easiest answer (if there are multiple). When I installed the printer, I renamed it to "ICS Label Printer". Here's how to change the options to allow pass-through ZPL commands:
Right-click on the "ICS Label Printer" and choose "Properties".
On the "General" tab, click on the "Printing Preferences..." button.
On the "Advanced Setup" tab, click on the "Other" button.
Make sure there is a check in the box labeled "Enable Passthrough Mode".
Make sure the "Start sequence:" is "${".
Make sure the "End sequence:" is "}$".
Click on the "Close" button.
Click on the "OK" button.
Click on the "OK" button.
In my code, I just have to add "${" to the beginning of my ZPL and "}$" to the end and print it as plain text. This is with the "Windows driver for ZDesigner LP 2844-Z printer Version 2.6.42 (Build 2382)". Works like a charm!
I've found yet an easier way to write to a Zebra printer over a COM port. I went to the Windows control panel and added a new printer. For the port, I chose COM1 (the port the printer was plugged in to). I used a "Generic / Text Only" printer driver. I disabled the print spooler (a standard option in the printer preferences) as well as all advanced printing options. Now, I can just print any string to that printer and if the string contains ZPL, the printer renders the ZPL just fine! No need for special "start sequences" or funky stuff like that. Yay for simplicity!
Visual Studio C# solution (found at http://support.microsoft.com/kb/322091)
Step 1.) Create class RawPrinterHelper...
using System;
using System.IO;
using System.Runtime.InteropServices;
public class RawPrinterHelper
{
// Structure and API declarions:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)]
public string pDocName;
[MarshalAs(UnmanagedType.LPStr)]
public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)]
public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "My C#.NET RAW Document";
di.pDataType = "RAW";
// Open the printer.
if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
{
// Start a document.
if (StartDocPrinter(hPrinter, 1, di))
{
// Start a page.
if (StartPagePrinter(hPrinter))
{
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if (bSuccess == false)
{
dwError = Marshal.GetLastWin32Error();
}
return bSuccess;
}
public static bool SendFileToPrinter(string szPrinterName, string szFileName)
{
// Open the file.
FileStream fs = new FileStream(szFileName, FileMode.Open);
// Create a BinaryReader on the file.
BinaryReader br = new BinaryReader(fs);
// Dim an array of bytes big enough to hold the file's contents.
Byte[] bytes = new Byte[fs.Length];
bool bSuccess = false;
// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);
int nLength;
nLength = Convert.ToInt32(fs.Length);
// Read the contents of the file into the array.
bytes = br.ReadBytes(nLength);
// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return bSuccess;
}
public static bool SendStringToPrinter(string szPrinterName, string szString)
{
IntPtr pBytes;
Int32 dwCount;
// How many characters are in the string?
dwCount = szString.Length;
// Assume that the printer is expecting ANSI text, and then convert
// the string to ANSI text.
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
// Send the converted ANSI string to the printer.
SendBytesToPrinter(szPrinterName, pBytes, dwCount);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
}
Step 2.) Create a form with text box and button (text box will hold the ZPL to send in this example). In button click event add code...
private void button1_Click(object sender, EventArgs e)
{
// Allow the user to select a printer.
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new PrinterSettings();
if (DialogResult.OK == pd.ShowDialog(this))
{
// Send a printer-specific to the printer.
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, textBox1.Text);
MessageBox.Show("Data sent to printer.");
}
else
{
MessageBox.Show("Data not sent to printer.");
}
}
With this solution, you can tweak to meet specific requirements. Perhaps hardcode the specific printer. Perhaps derive the ZPL text dynamically rather than from a text box. Whatever. Perhaps you don't need a graphical interface, but this shows how to send the ZPL. Your use depends on your needs.
You haven't mentioned a language, so I'm going to give you some some hints how to do it with the straight Windows API in C.
First, open a connection to the printer with OpenPrinter. Next, start a document with StartDocPrinter having the pDatatype field of the DOC_INFO_1 structure set to "RAW" - this tells the printer driver not to encode anything going to the printer, but to pass it along unchanged. Use StartPagePrinter to indicate the first page, WritePrinter to send the data to the printer, and close it with EndPagePrinter, EndDocPrinter and ClosePrinter when done.
ZPL is the correct way to go. In most cases it is correct to use a driver that abstracts to GDI commands; however Zebra label printers are a special case. The best way to print to a Zebra printer is to generate ZPL directly. Note that the actual printer driver for a Zebra printer is a "plain text" printer - there is not a "driver" that could be updated or changed in the sense we think of most printers having drivers. It's just a driver in the absolute minimalist sense.
Install an share your printer: \localhost\zebra
Send ZPL as text, try with copy first:
copy file.zpl \localhost\zebra
very simple, almost no coding.
I spent 8 hours to do that.
It is simple...
You shoud have a code like that:
private const int GENERIC_WRITE = 0x40000000;
//private const int OPEN_EXISTING = 3;
private const int OPEN_EXISTING = 1;
private const int FILE_SHARE_WRITE = 0x2;
private StreamWriter _fileWriter;
private FileStream _outFile;
private int _hPort;
Change that variable content from 3 (open file already exist) to 1 (create a new file).
It'll work at Windows 7 and XP.
Found amazing simple solution - working for Chrome (Windows, not tested on Mac)
Zebra ZP 450
Go here Zebra Generic Text
Go precisely by the manual
No COM1 or any other ports needed - USB is enough
When done (named the printer ZTEXT), does not matter if it won't print a test page
Turn of Spooling and enable direct printing in Printer Preferences - 1 note here 1 printer is ZP450 CPT and other ZP450 only - on the other one I do not even need to turn off spooling and it worked.
Go to Chrome and printing ZPL from there with Chrome Print Dialog Box by selecting the ZTEXT printer (Generic / Text) Printer (Do not choose Windows Dialog Box) - we needed this for Chrome to be working
For anybody torturing themselves with the above in 2021, if you're in the .NET world then get hold of the RawPrint NuGet package.
From there to print your ZPL string directly to the printer, bypassing drivers, it's:
IPrinter printer = new Printer();
printer.PrintRawStream(#"Your Printer Name", GenerateStreamFromString(yourZplString), #"docname");