How do I know if the timer is running or already started? Without waiting the time is elapsed?
UINT_PTR nID = SetTimer(123, 60x1000, NULL); // Info after 1 Min.
bool bTimerStarted = false; // do I need this bool var to check the state of the timer?
if (nID == 123)
bTimerStarted = true;
You cannot. There is no API to query whether any given timer exists, without also resetting that timer (which SetTimer can do).
Then again, I cannot think of a situation where this would be required. Unless you've designed yourself into a corner previously. In that case, solve the architectural issue, and you'll find that you won't need this information either.
Related
I'm trying to spoof keystrokes; to be a bit more precise: I'm replaying a number of keystrokes which should all get sent at a certain time - sometimes several at the same time (or at least as close together as reasonably possible).
Implementing this using XTestFakeKeyEvent, I've come across a problem. While what I've written so far mostly works as it is intended and sends the events at the correct time, sometimes a number of them will fail. XTestFakeKeyEvent never returns zero (which would indicate failure), but these events never seem to reach the application I'm trying to send them to. I suspect that this might be due to the frequency of calls being too high (sometimes 100+/second) as it looks like it's more prone to fail when there's a large number of keystrokes/second.
A little program to illustrate what I'm doing, incomplete and without error checks for the sake of conciseness:
// #includes ...
struct action {
int time; // Time where this should be executed.
int down; // Keydown or keyup?
int code; // The VK to simulate the event for.
};
Display *display;
int nactions; // actions array length.
struct action *actions; // Array of actions we'll want to "execute".
int main(void)
{
display = XOpenDisplay(NULL);
nactions = get_actions(&actions);
int cur_time;
int cur_i = 0;
struct action *cur_action;
// While there's still actions to execute.
while (cur_i < nactions) {
cur_time = get_time();
cur_action = actions + cur_i;
// For each action that is (over)due.
while ((cur_action = actions + cur_i)->time <= cur_time) {
cur_i++;
XTestFakeKeyEvent(display, cur_action->code,
cur_action->down, CurrentTime);
XFlush(display);
}
// Sleep for 1ms.
nanosleep((struct timespec[]){{0, 1000000L}}, NULL);
}
}
I realize that the code above is very specific to my case, but I suspect that this is a broader problem - which is also why I'm asking this here.
Is there a limit to how often you can/should flush XEvents? Could the application I'm sending this to be the issue, maybe failing to read them quickly enough?
It's been a little while but after some tinkering, it turned out that my delay between key down and key up was simply too low. After setting it to 15ms the application registered the actions as keystrokes properly and (still) with very high accuracy.
I feel a little silly in retrospect, but I do feel like this might be something others could stumble over as well.
Anybody got this problem, anyway I didn't find an answer. The code is simple:
void CbDlg::OnBnClickedOk()
{
for(int i=0; i<1000; i++)
{
HRSRC hRes = ::FindResource(NULL, MAKEINTRESOURCE(IDR_MAINFRAME), RT_GROUP_ICON);
HGLOBAL hResLoad = ::LoadResource(NULL, hRes);
BYTE* pIconBytes = (BYTE*)::LockResource(hResLoad);
int nId = ::LookupIconIdFromDirectory(pIconBytes, TRUE);
hRes = ::FindResource(NULL, MAKEINTRESOURCE(nId), RT_ICON);
DWORD read = ::SizeofResource(NULL ,hRes);
hResLoad = ::LoadResource(NULL, hRes);
pIconBytes = (BYTE*)::LockResource(hResLoad);
if(pIconBytes != NULL)
{
HICON hIcon = ::CreateIconFromResource(pIconBytes, read, TRUE, 0x00030000);
DWORD e = ::GetLastError();
if(hIcon != NULL)
{
::DestroyIcon(hIcon);
}
}
}
}
If I click the Ok button four times (On my computer), CreateIconFromResource start to return NULL (It worked fine before and I could even draw out the icon). As to the GetLastError, it's always return 6 whatever CreateIconFromResource return NULL or not.
When this problem happened, if I drag the title bar to move, UI crashed, see the pictrue.
Of course you can understand this piece of code is just a demo, my real business need to call CreateIconFromResource thousands of times just like this.
UPDATE:
According to Hans' suggestion, I keep tracking the Handles/USER Objects/GDI objects, and found that USER Objects grows 1000 and GDI objects grows 2000 against each clicking to OK button (handles didn't grow), and GDI objects is 9999 when problem happens. But how to release them correctly, when I finish to use? I didn't use that much at one time, but need to load, release, load again, release again... Just like this demo. As MSDN document, I called DestroyIcon for every HICON. What else do I need to do, to finally release the USER/GDI objects?
I found the answer. The success or failure is all due to MSDN.
It says:
"The CreateIconFromResource function calls CreateIconFromResourceEx passing LR_DEFAULTSIZE|LR_SHARED as flags" AND "Do not use this function(DestroyIcon) to destroy a shared icon"
But It also says:
"When you are finished using the icon, destroy it using the DestroyIcon function" in CreateIconFromResource's document.
Actually, the second statement is WRONG.
So, the solution is, using CreateIconFromResourceEx without LR_SHARED, and DestroyIcon every HICON after using.
I'm debugging Qt5.3.1 on Mac, because my program freezes sometimes (intermittent ). I discovered that it is because the QTimer can't work properly.
In Qt code, they use the following two lines to trigger function activateTimersSourceCallback
CFRunLoopSourceSignal(d->activateTimersSourceRef);
CFRunLoopWakeUp(mainRunLoop());
void QCocoaEventDispatcherPrivate::activateTimersSourceCallback(void *info)
{
static int counter = 0;
NSLog(#"finished activeteTimersSourceCallback %d", counter++);
}
but sometimes, these two lines doesn't work, activateTimersSourceCallback won't get called.
I googled, but I couldn't find any solution? is this a known OS bug?
the initialization details:
// keep our sources running when modal loops are running
CFRunLoopAddCommonMode(mainRunLoop(), (CFStringRef) NSModalPanelRunLoopMode);
CFRunLoopSourceContext context;
bzero(&context, sizeof(CFRunLoopSourceContext));
context.info = d;
context.equal = runLoopSourceEqualCallback;
// source used to activate timers
context.perform = QCocoaEventDispatcherPrivate::activateTimersSourceCallback;
d->activateTimersSourceRef = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
Q_ASSERT(d->activateTimersSourceRef);
CFRunLoopAddSource(mainRunLoop(), d->activateTimersSourceRef, kCFRunLoopCommonModes);
Such behavior very likely can occur when UI event loop is overloaded with events or some business logic takes too long time. You should to check your business logic and move it to separate thread or run asynchronous.
I'm looking for a simple way to perform an action/method after a delay of n seconds. The thing I found a few examples but they seem overly complex for when on my last platform, iOS, it was just
[self performSelector:#selector(methodname) withDelay:3];
Any tips or code snippets would be much appreciated.
You can also use Scheduler.Dispatcher from Microsoft.Phone.Reactive:
Scheduler.Dispatcher.Schedule(MethodName, TimeSpan.FromSeconds(5));
private void MethodName()
{
// This happens 5 seconds later (on the UI thread)
}
DispatcherTimer DelayedTimer = new DispatcherTimer()
{
Interval = TimeSpan.FromSeconds(5)
};
DelayedTimer.Tick += (s, e) =>
{
//perform action
DelayedTimer.Stop();
}
DelayedTimer.Start();
For Windows Phone 8 you can use
await Task.Delay(milliseconds);
DispatcherTimer timer = new DispatcherTimer();
timer.Tick += (s, e) =>
{
// do some very quick work here
// update the UI
StatusText.Text = DateTime.Now.Second.ToString();
};
timer.Interval = TimeSpan.FromSeconds(1);
timer.Start();
Note that what you're doing here is interrupting the UI thread, not really running anything on a separate thread. It's not suitable for anything long-running and cpu-intensive, but rather something where you need to execute on a regular interval. Clock UI updates are a perfect example.
Also Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.
For more information use this link
If you want to use Timer for the background task then use the
System.Threading.Timer instead of DispatcherTimer
For more information use this link
How would one click on a button, wait for an event like blur and then get the pagesource of the site?
I know i can use the getPagesource() method, but I only wanna do this after a jquery loading image has been shown.
If the blur event results in a visible effect, you could wait for that effect, like waiting for an image to be shown.
Otherwise, if there is no visible effect from that event, you would need a "testing hook" to tell your test that the function associated with that event already ran, like a javascript variable being set to a known value that you could query in the test.
For both cases you could use an explicit wait for the condition, like what is shown in the documentation:
http://seleniumhq.org/docs/04_webdriver_advanced.html#explicit-and-implicit-waits
EDIT:
Regarding your comment, Nyegaard, you could use an explicit wait like this one:
WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
Boolean expectedTextAppeared =
(new WebDriverWait(driver, 10))
.until(ExpectedConditions.textToBePresentInElement(
By.id("ctl00_content_createnewschema_modalAlert_alertMessage"), "textYoureExpecting"));
This code will wait for "textYoureExpecting" to appear in the span with a timeout of 10 seconds. If it takes more time for it to appear, you just need to adjust the timeout.
For all AJAX requests in the webpage I use jQuery.Active flag to determine if the page is loaded or not. If jQuery.Active is non-zero that means those are the number of active requests the browser is dealing with. When it comes down to zero, that means number of active requests are none. I haven't used this flag for blur events, but you might as well give it a try. You should definitely use implicitly and explicitly waits Luiz suggested. Here is a function that waits for 5 minutes for active requests to complete. You could perhaps parameterize that, add try, catch etc.
public int waitforAJAXRequestsToComplete(){
long start = System.currentTimeMillis();
long duration;
boolean ajaxNotReady = true;
while(ajaxNotReady){
if(((JavascriptExecutor)driver).executeScript("return jQuery.active").toString().equals("0"))
return 0;
duration = System.currentTimeMillis() - start;
duration = (long) (duration/(60*1000F));
if(duration>5.0)
return 1;
}
return 1;
}