partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
Evolutionary.tf_step
Creates the TensorFlow operations for performing an optimization step. Args: time: Time tensor. variables: List of variables to optimize. arguments: Dict of arguments for callables, like fn_loss. fn_loss: A callable returning the loss of the current model. **kwargs: Additional arguments, not used. Returns: List of delta tensors corresponding to the updates for each optimized variable.
tensorforce/core/optimizers/evolutionary.py
def tf_step( self, time, variables, arguments, fn_loss, **kwargs ): """ Creates the TensorFlow operations for performing an optimization step. Args: time: Time tensor. variables: List of variables to optimize. arguments: Dict of arguments for callables, like fn_loss. fn_loss: A callable returning the loss of the current model. **kwargs: Additional arguments, not used. Returns: List of delta tensors corresponding to the updates for each optimized variable. """ unperturbed_loss = fn_loss(**arguments) # First sample perturbations = [tf.random_normal(shape=util.shape(variable)) * self.learning_rate for variable in variables] applied = self.apply_step(variables=variables, deltas=perturbations) with tf.control_dependencies(control_inputs=(applied,)): perturbed_loss = fn_loss(**arguments) direction = tf.sign(x=(unperturbed_loss - perturbed_loss)) deltas_sum = [direction * perturbation for perturbation in perturbations] if self.unroll_loop: # Unrolled for loop previous_perturbations = perturbations for sample in xrange(self.num_samples): with tf.control_dependencies(control_inputs=deltas_sum): perturbations = [tf.random_normal(shape=util.shape(variable)) * self.learning_rate for variable in variables] perturbation_deltas = [ pert - prev_pert for pert, prev_pert in zip(perturbations, previous_perturbations) ] applied = self.apply_step(variables=variables, deltas=perturbation_deltas) previous_perturbations = perturbations with tf.control_dependencies(control_inputs=(applied,)): perturbed_loss = fn_loss(**arguments) direction = tf.sign(x=(unperturbed_loss - perturbed_loss)) deltas_sum = [delta + direction * perturbation for delta, perturbation in zip(deltas_sum, perturbations)] else: # TensorFlow while loop def body(iteration, deltas_sum, previous_perturbations): with tf.control_dependencies(control_inputs=deltas_sum): perturbations = [tf.random_normal(shape=util.shape(variable)) * self.learning_rate for variable in variables] perturbation_deltas = [ pert - prev_pert for pert, prev_pert in zip(perturbations, previous_perturbations) ] applied = self.apply_step(variables=variables, deltas=perturbation_deltas) with tf.control_dependencies(control_inputs=(applied,)): perturbed_loss = fn_loss(**arguments) direction = tf.sign(x=(unperturbed_loss - perturbed_loss)) deltas_sum = [delta + direction * perturbation for delta, perturbation in zip(deltas_sum, perturbations)] return iteration + 1, deltas_sum, perturbations def cond(iteration, deltas_sum, previous_perturbation): return iteration < self.num_samples - 1 _, deltas_sum, perturbations = tf.while_loop(cond=cond, body=body, loop_vars=(0, deltas_sum, perturbations)) with tf.control_dependencies(control_inputs=deltas_sum): deltas = [delta / self.num_samples for delta in deltas_sum] perturbation_deltas = [delta - pert for delta, pert in zip(deltas, perturbations)] applied = self.apply_step(variables=variables, deltas=perturbation_deltas) with tf.control_dependencies(control_inputs=(applied,)): # Trivial operation to enforce control dependency return [delta + 0.0 for delta in deltas]
def tf_step( self, time, variables, arguments, fn_loss, **kwargs ): """ Creates the TensorFlow operations for performing an optimization step. Args: time: Time tensor. variables: List of variables to optimize. arguments: Dict of arguments for callables, like fn_loss. fn_loss: A callable returning the loss of the current model. **kwargs: Additional arguments, not used. Returns: List of delta tensors corresponding to the updates for each optimized variable. """ unperturbed_loss = fn_loss(**arguments) # First sample perturbations = [tf.random_normal(shape=util.shape(variable)) * self.learning_rate for variable in variables] applied = self.apply_step(variables=variables, deltas=perturbations) with tf.control_dependencies(control_inputs=(applied,)): perturbed_loss = fn_loss(**arguments) direction = tf.sign(x=(unperturbed_loss - perturbed_loss)) deltas_sum = [direction * perturbation for perturbation in perturbations] if self.unroll_loop: # Unrolled for loop previous_perturbations = perturbations for sample in xrange(self.num_samples): with tf.control_dependencies(control_inputs=deltas_sum): perturbations = [tf.random_normal(shape=util.shape(variable)) * self.learning_rate for variable in variables] perturbation_deltas = [ pert - prev_pert for pert, prev_pert in zip(perturbations, previous_perturbations) ] applied = self.apply_step(variables=variables, deltas=perturbation_deltas) previous_perturbations = perturbations with tf.control_dependencies(control_inputs=(applied,)): perturbed_loss = fn_loss(**arguments) direction = tf.sign(x=(unperturbed_loss - perturbed_loss)) deltas_sum = [delta + direction * perturbation for delta, perturbation in zip(deltas_sum, perturbations)] else: # TensorFlow while loop def body(iteration, deltas_sum, previous_perturbations): with tf.control_dependencies(control_inputs=deltas_sum): perturbations = [tf.random_normal(shape=util.shape(variable)) * self.learning_rate for variable in variables] perturbation_deltas = [ pert - prev_pert for pert, prev_pert in zip(perturbations, previous_perturbations) ] applied = self.apply_step(variables=variables, deltas=perturbation_deltas) with tf.control_dependencies(control_inputs=(applied,)): perturbed_loss = fn_loss(**arguments) direction = tf.sign(x=(unperturbed_loss - perturbed_loss)) deltas_sum = [delta + direction * perturbation for delta, perturbation in zip(deltas_sum, perturbations)] return iteration + 1, deltas_sum, perturbations def cond(iteration, deltas_sum, previous_perturbation): return iteration < self.num_samples - 1 _, deltas_sum, perturbations = tf.while_loop(cond=cond, body=body, loop_vars=(0, deltas_sum, perturbations)) with tf.control_dependencies(control_inputs=deltas_sum): deltas = [delta / self.num_samples for delta in deltas_sum] perturbation_deltas = [delta - pert for delta, pert in zip(deltas, perturbations)] applied = self.apply_step(variables=variables, deltas=perturbation_deltas) with tf.control_dependencies(control_inputs=(applied,)): # Trivial operation to enforce control dependency return [delta + 0.0 for delta in deltas]
[ "Creates", "the", "TensorFlow", "operations", "for", "performing", "an", "optimization", "step", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/evolutionary.py#L52-L132
[ "def", "tf_step", "(", "self", ",", "time", ",", "variables", ",", "arguments", ",", "fn_loss", ",", "*", "*", "kwargs", ")", ":", "unperturbed_loss", "=", "fn_loss", "(", "*", "*", "arguments", ")", "# First sample", "perturbations", "=", "[", "tf", "."...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
GlobalOptimizer.tf_step
Keyword Args: global_variables: List of global variables to apply the proposed optimization step to. Returns: List of delta tensors corresponding to the updates for each optimized variable.
tensorforce/core/optimizers/global_optimizer.py
def tf_step(self, time, variables, **kwargs): """ Keyword Args: global_variables: List of global variables to apply the proposed optimization step to. Returns: List of delta tensors corresponding to the updates for each optimized variable. """ global_variables = kwargs["global_variables"] assert all( util.shape(global_variable) == util.shape(local_variable) for global_variable, local_variable in zip(global_variables, variables) ) local_deltas = self.optimizer.step(time=time, variables=variables, **kwargs) with tf.control_dependencies(control_inputs=local_deltas): applied = self.optimizer.apply_step(variables=global_variables, deltas=local_deltas) with tf.control_dependencies(control_inputs=(applied,)): update_deltas = list() for global_variable, local_variable in zip(global_variables, variables): delta = global_variable - local_variable update_deltas.append(delta) applied = self.apply_step(variables=variables, deltas=update_deltas) # TODO: Update time, episode, etc (like in Synchronization)? with tf.control_dependencies(control_inputs=(applied,)): return [local_delta + update_delta for local_delta, update_delta in zip(local_deltas, update_deltas)]
def tf_step(self, time, variables, **kwargs): """ Keyword Args: global_variables: List of global variables to apply the proposed optimization step to. Returns: List of delta tensors corresponding to the updates for each optimized variable. """ global_variables = kwargs["global_variables"] assert all( util.shape(global_variable) == util.shape(local_variable) for global_variable, local_variable in zip(global_variables, variables) ) local_deltas = self.optimizer.step(time=time, variables=variables, **kwargs) with tf.control_dependencies(control_inputs=local_deltas): applied = self.optimizer.apply_step(variables=global_variables, deltas=local_deltas) with tf.control_dependencies(control_inputs=(applied,)): update_deltas = list() for global_variable, local_variable in zip(global_variables, variables): delta = global_variable - local_variable update_deltas.append(delta) applied = self.apply_step(variables=variables, deltas=update_deltas) # TODO: Update time, episode, etc (like in Synchronization)? with tf.control_dependencies(control_inputs=(applied,)): return [local_delta + update_delta for local_delta, update_delta in zip(local_deltas, update_deltas)]
[ "Keyword", "Args", ":", "global_variables", ":", "List", "of", "global", "variables", "to", "apply", "the", "proposed", "optimization", "step", "to", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/global_optimizer.py#L44-L76
[ "def", "tf_step", "(", "self", ",", "time", ",", "variables", ",", "*", "*", "kwargs", ")", ":", "global_variables", "=", "kwargs", "[", "\"global_variables\"", "]", "assert", "all", "(", "util", ".", "shape", "(", "global_variable", ")", "==", "util", "...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
KFAC.computeStatsEigen
compute the eigen decomp using copied var stats to avoid concurrent read/write from other queue
tensorforce/core/optimizers/kfac.py
def computeStatsEigen(self): """ compute the eigen decomp using copied var stats to avoid concurrent read/write from other queue """ # TO-DO: figure out why this op has delays (possibly moving # eigenvectors around?) with tf.device('/cpu:0'): def removeNone(tensor_list): local_list = [] for item in tensor_list: if item is not None: local_list.append(item) return local_list def copyStats(var_list): print("copying stats to buffer tensors before eigen decomp") redundant_stats = {} copied_list = [] for item in var_list: if item is not None: if item not in redundant_stats: if self._use_float64: redundant_stats[item] = tf.cast( tf.identity(item), tf.float64) else: redundant_stats[item] = tf.identity(item) copied_list.append(redundant_stats[item]) else: copied_list.append(None) return copied_list #stats = [copyStats(self.fStats), copyStats(self.bStats)] #stats = [self.fStats, self.bStats] stats_eigen = self.stats_eigen computedEigen = {} eigen_reverse_lookup = {} updateOps = [] # sync copied stats # with tf.control_dependencies(removeNone(stats[0]) + # removeNone(stats[1])): with tf.control_dependencies([]): for stats_var in stats_eigen: if stats_var not in computedEigen: eigens = tf.self_adjoint_eig(stats_var) e = eigens[0] Q = eigens[1] if self._use_float64: e = tf.cast(e, tf.float32) Q = tf.cast(Q, tf.float32) updateOps.append(e) updateOps.append(Q) computedEigen[stats_var] = {'e': e, 'Q': Q} eigen_reverse_lookup[e] = stats_eigen[stats_var]['e'] eigen_reverse_lookup[Q] = stats_eigen[stats_var]['Q'] self.eigen_reverse_lookup = eigen_reverse_lookup self.eigen_update_list = updateOps return updateOps
def computeStatsEigen(self): """ compute the eigen decomp using copied var stats to avoid concurrent read/write from other queue """ # TO-DO: figure out why this op has delays (possibly moving # eigenvectors around?) with tf.device('/cpu:0'): def removeNone(tensor_list): local_list = [] for item in tensor_list: if item is not None: local_list.append(item) return local_list def copyStats(var_list): print("copying stats to buffer tensors before eigen decomp") redundant_stats = {} copied_list = [] for item in var_list: if item is not None: if item not in redundant_stats: if self._use_float64: redundant_stats[item] = tf.cast( tf.identity(item), tf.float64) else: redundant_stats[item] = tf.identity(item) copied_list.append(redundant_stats[item]) else: copied_list.append(None) return copied_list #stats = [copyStats(self.fStats), copyStats(self.bStats)] #stats = [self.fStats, self.bStats] stats_eigen = self.stats_eigen computedEigen = {} eigen_reverse_lookup = {} updateOps = [] # sync copied stats # with tf.control_dependencies(removeNone(stats[0]) + # removeNone(stats[1])): with tf.control_dependencies([]): for stats_var in stats_eigen: if stats_var not in computedEigen: eigens = tf.self_adjoint_eig(stats_var) e = eigens[0] Q = eigens[1] if self._use_float64: e = tf.cast(e, tf.float32) Q = tf.cast(Q, tf.float32) updateOps.append(e) updateOps.append(Q) computedEigen[stats_var] = {'e': e, 'Q': Q} eigen_reverse_lookup[e] = stats_eigen[stats_var]['e'] eigen_reverse_lookup[Q] = stats_eigen[stats_var]['Q'] self.eigen_reverse_lookup = eigen_reverse_lookup self.eigen_update_list = updateOps return updateOps
[ "compute", "the", "eigen", "decomp", "using", "copied", "var", "stats", "to", "avoid", "concurrent", "read", "/", "write", "from", "other", "queue" ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/kfac.py#L550-L606
[ "def", "computeStatsEigen", "(", "self", ")", ":", "# TO-DO: figure out why this op has delays (possibly moving", "# eigenvectors around?)", "with", "tf", ".", "device", "(", "'/cpu:0'", ")", ":", "def", "removeNone", "(", "tensor_list", ")", ":", "local_list", "=", "...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
KFAC.tf_step
Creates the TensorFlow operations for performing an optimization step on the given variables, including actually changing the values of the variables. Args: time: Time tensor. Not used for this optimizer. variables: List of variables to optimize. **kwargs: fn_loss : loss function tensor to differentiate. Returns: List of delta tensors corresponding to the updates for each optimized variable.
tensorforce/core/optimizers/kfac.py
def tf_step(self, time, variables, **kwargs): """ Creates the TensorFlow operations for performing an optimization step on the given variables, including actually changing the values of the variables. Args: time: Time tensor. Not used for this optimizer. variables: List of variables to optimize. **kwargs: fn_loss : loss function tensor to differentiate. Returns: List of delta tensors corresponding to the updates for each optimized variable. """ fn_loss = kwargs["fn_loss"] if variables is None: variables = tf.trainable_variables return tf.gradients(fn_loss, variables)
def tf_step(self, time, variables, **kwargs): """ Creates the TensorFlow operations for performing an optimization step on the given variables, including actually changing the values of the variables. Args: time: Time tensor. Not used for this optimizer. variables: List of variables to optimize. **kwargs: fn_loss : loss function tensor to differentiate. Returns: List of delta tensors corresponding to the updates for each optimized variable. """ fn_loss = kwargs["fn_loss"] if variables is None: variables = tf.trainable_variables return tf.gradients(fn_loss, variables)
[ "Creates", "the", "TensorFlow", "operations", "for", "performing", "an", "optimization", "step", "on", "the", "given", "variables", "including", "actually", "changing", "the", "values", "of", "the", "variables", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/kfac.py#L918-L935
[ "def", "tf_step", "(", "self", ",", "time", ",", "variables", ",", "*", "*", "kwargs", ")", ":", "fn_loss", "=", "kwargs", "[", "\"fn_loss\"", "]", "if", "variables", "is", "None", ":", "variables", "=", "tf", ".", "trainable_variables", "return", "tf", ...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
KFAC.apply_step
Applies the given (and already calculated) step deltas to the variable values. Args: variables: List of variables. deltas: List of deltas of same length. loss_sampled : the sampled loss Returns: The step-applied operation. A tf.group of tf.assign_add ops.
tensorforce/core/optimizers/kfac.py
def apply_step(self, variables, deltas, loss_sampled): """ Applies the given (and already calculated) step deltas to the variable values. Args: variables: List of variables. deltas: List of deltas of same length. loss_sampled : the sampled loss Returns: The step-applied operation. A tf.group of tf.assign_add ops. """ update_stats_op = self.compute_and_apply_stats( loss_sampled, var_list=var_list) grads = [(a, b) for a, b in zip(deltas, varlist)] kfacOptim, _ = self.apply_gradients_kfac(grads) return kfacOptim
def apply_step(self, variables, deltas, loss_sampled): """ Applies the given (and already calculated) step deltas to the variable values. Args: variables: List of variables. deltas: List of deltas of same length. loss_sampled : the sampled loss Returns: The step-applied operation. A tf.group of tf.assign_add ops. """ update_stats_op = self.compute_and_apply_stats( loss_sampled, var_list=var_list) grads = [(a, b) for a, b in zip(deltas, varlist)] kfacOptim, _ = self.apply_gradients_kfac(grads) return kfacOptim
[ "Applies", "the", "given", "(", "and", "already", "calculated", ")", "step", "deltas", "to", "the", "variable", "values", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/kfac.py#L937-L953
[ "def", "apply_step", "(", "self", ",", "variables", ",", "deltas", ",", "loss_sampled", ")", ":", "update_stats_op", "=", "self", ".", "compute_and_apply_stats", "(", "loss_sampled", ",", "var_list", "=", "var_list", ")", "grads", "=", "[", "(", "a", ",", ...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
KFAC.minimize
Performs an optimization step. Args: time: Time tensor. Not used for this variables: List of variables to optimize. **kwargs: fn_loss : loss function tensor that is differentiated sampled_loss : the sampled loss from running the model. Returns: The optimization operation.
tensorforce/core/optimizers/kfac.py
def minimize(self, time, variables, **kwargs): """ Performs an optimization step. Args: time: Time tensor. Not used for this variables: List of variables to optimize. **kwargs: fn_loss : loss function tensor that is differentiated sampled_loss : the sampled loss from running the model. Returns: The optimization operation. """ loss = kwargs["fn_loss"] sampled_loss = kwargs["sampled_loss"] min_op, _ = self.minimize_(loss, sampled_loss, var_list=variables) return min_op
def minimize(self, time, variables, **kwargs): """ Performs an optimization step. Args: time: Time tensor. Not used for this variables: List of variables to optimize. **kwargs: fn_loss : loss function tensor that is differentiated sampled_loss : the sampled loss from running the model. Returns: The optimization operation. """ loss = kwargs["fn_loss"] sampled_loss = kwargs["sampled_loss"] min_op, _ = self.minimize_(loss, sampled_loss, var_list=variables) return min_op
[ "Performs", "an", "optimization", "step", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/kfac.py#L955-L973
[ "def", "minimize", "(", "self", ",", "time", ",", "variables", ",", "*", "*", "kwargs", ")", ":", "loss", "=", "kwargs", "[", "\"fn_loss\"", "]", "sampled_loss", "=", "kwargs", "[", "\"sampled_loss\"", "]", "min_op", ",", "_", "=", "self", ".", "minimi...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
QDemoModel.setup_components_and_tf_funcs
Constructs the extra Replay memory.
tensorforce/models/q_demo_model.py
def setup_components_and_tf_funcs(self, custom_getter=None): """ Constructs the extra Replay memory. """ custom_getter = super(QDemoModel, self).setup_components_and_tf_funcs(custom_getter) self.demo_memory = Replay( states=self.states_spec, internals=self.internals_spec, actions=self.actions_spec, include_next_states=True, capacity=self.demo_memory_capacity, scope='demo-replay', summary_labels=self.summary_labels ) # Import demonstration optimization. self.fn_import_demo_experience = tf.make_template( name_='import-demo-experience', func_=self.tf_import_demo_experience, custom_getter_=custom_getter ) # Demonstration loss. self.fn_demo_loss = tf.make_template( name_='demo-loss', func_=self.tf_demo_loss, custom_getter_=custom_getter ) # Combined loss. self.fn_combined_loss = tf.make_template( name_='combined-loss', func_=self.tf_combined_loss, custom_getter_=custom_getter ) # Demonstration optimization. self.fn_demo_optimization = tf.make_template( name_='demo-optimization', func_=self.tf_demo_optimization, custom_getter_=custom_getter ) return custom_getter
def setup_components_and_tf_funcs(self, custom_getter=None): """ Constructs the extra Replay memory. """ custom_getter = super(QDemoModel, self).setup_components_and_tf_funcs(custom_getter) self.demo_memory = Replay( states=self.states_spec, internals=self.internals_spec, actions=self.actions_spec, include_next_states=True, capacity=self.demo_memory_capacity, scope='demo-replay', summary_labels=self.summary_labels ) # Import demonstration optimization. self.fn_import_demo_experience = tf.make_template( name_='import-demo-experience', func_=self.tf_import_demo_experience, custom_getter_=custom_getter ) # Demonstration loss. self.fn_demo_loss = tf.make_template( name_='demo-loss', func_=self.tf_demo_loss, custom_getter_=custom_getter ) # Combined loss. self.fn_combined_loss = tf.make_template( name_='combined-loss', func_=self.tf_combined_loss, custom_getter_=custom_getter ) # Demonstration optimization. self.fn_demo_optimization = tf.make_template( name_='demo-optimization', func_=self.tf_demo_optimization, custom_getter_=custom_getter ) return custom_getter
[ "Constructs", "the", "extra", "Replay", "memory", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L103-L147
[ "def", "setup_components_and_tf_funcs", "(", "self", ",", "custom_getter", "=", "None", ")", ":", "custom_getter", "=", "super", "(", "QDemoModel", ",", "self", ")", ".", "setup_components_and_tf_funcs", "(", "custom_getter", ")", "self", ".", "demo_memory", "=", ...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
QDemoModel.tf_import_demo_experience
Imports a single experience to memory.
tensorforce/models/q_demo_model.py
def tf_import_demo_experience(self, states, internals, actions, terminal, reward): """ Imports a single experience to memory. """ return self.demo_memory.store( states=states, internals=internals, actions=actions, terminal=terminal, reward=reward )
def tf_import_demo_experience(self, states, internals, actions, terminal, reward): """ Imports a single experience to memory. """ return self.demo_memory.store( states=states, internals=internals, actions=actions, terminal=terminal, reward=reward )
[ "Imports", "a", "single", "experience", "to", "memory", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L153-L163
[ "def", "tf_import_demo_experience", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ")", ":", "return", "self", ".", "demo_memory", ".", "store", "(", "states", "=", "states", ",", "internals", "=", "internals", ...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
QDemoModel.tf_demo_loss
Extends the q-model loss via the dqfd large-margin loss.
tensorforce/models/q_demo_model.py
def tf_demo_loss(self, states, actions, terminal, reward, internals, update, reference=None): """ Extends the q-model loss via the dqfd large-margin loss. """ embedding = self.network.apply(x=states, internals=internals, update=update) deltas = list() for name in sorted(actions): action = actions[name] distr_params = self.distributions[name].parameterize(x=embedding) state_action_value = self.distributions[name].state_action_value(distr_params=distr_params, action=action) # Create the supervised margin loss # Zero for the action taken, one for all other actions, now multiply by expert margin if self.actions_spec[name]['type'] == 'bool': num_actions = 2 action = tf.cast(x=action, dtype=util.tf_dtype('int')) else: num_actions = self.actions_spec[name]['num_actions'] one_hot = tf.one_hot(indices=action, depth=num_actions) ones = tf.ones_like(tensor=one_hot, dtype=tf.float32) inverted_one_hot = ones - one_hot # max_a([Q(s,a) + l(s,a_E,a)], l(s,a_E, a) is 0 for expert action and margin value for others state_action_values = self.distributions[name].state_action_value(distr_params=distr_params) state_action_values = state_action_values + inverted_one_hot * self.expert_margin supervised_selector = tf.reduce_max(input_tensor=state_action_values, axis=-1) # J_E(Q) = max_a([Q(s,a) + l(s,a_E,a)] - Q(s,a_E) delta = supervised_selector - state_action_value action_size = util.prod(self.actions_spec[name]['shape']) delta = tf.reshape(tensor=delta, shape=(-1, action_size)) deltas.append(delta) loss_per_instance = tf.reduce_mean(input_tensor=tf.concat(values=deltas, axis=1), axis=1) loss_per_instance = tf.square(x=loss_per_instance) return tf.reduce_mean(input_tensor=loss_per_instance, axis=0)
def tf_demo_loss(self, states, actions, terminal, reward, internals, update, reference=None): """ Extends the q-model loss via the dqfd large-margin loss. """ embedding = self.network.apply(x=states, internals=internals, update=update) deltas = list() for name in sorted(actions): action = actions[name] distr_params = self.distributions[name].parameterize(x=embedding) state_action_value = self.distributions[name].state_action_value(distr_params=distr_params, action=action) # Create the supervised margin loss # Zero for the action taken, one for all other actions, now multiply by expert margin if self.actions_spec[name]['type'] == 'bool': num_actions = 2 action = tf.cast(x=action, dtype=util.tf_dtype('int')) else: num_actions = self.actions_spec[name]['num_actions'] one_hot = tf.one_hot(indices=action, depth=num_actions) ones = tf.ones_like(tensor=one_hot, dtype=tf.float32) inverted_one_hot = ones - one_hot # max_a([Q(s,a) + l(s,a_E,a)], l(s,a_E, a) is 0 for expert action and margin value for others state_action_values = self.distributions[name].state_action_value(distr_params=distr_params) state_action_values = state_action_values + inverted_one_hot * self.expert_margin supervised_selector = tf.reduce_max(input_tensor=state_action_values, axis=-1) # J_E(Q) = max_a([Q(s,a) + l(s,a_E,a)] - Q(s,a_E) delta = supervised_selector - state_action_value action_size = util.prod(self.actions_spec[name]['shape']) delta = tf.reshape(tensor=delta, shape=(-1, action_size)) deltas.append(delta) loss_per_instance = tf.reduce_mean(input_tensor=tf.concat(values=deltas, axis=1), axis=1) loss_per_instance = tf.square(x=loss_per_instance) return tf.reduce_mean(input_tensor=loss_per_instance, axis=0)
[ "Extends", "the", "q", "-", "model", "loss", "via", "the", "dqfd", "large", "-", "margin", "loss", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L165-L204
[ "def", "tf_demo_loss", "(", "self", ",", "states", ",", "actions", ",", "terminal", ",", "reward", ",", "internals", ",", "update", ",", "reference", "=", "None", ")", ":", "embedding", "=", "self", ".", "network", ".", "apply", "(", "x", "=", "states"...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
QDemoModel.tf_combined_loss
Combines Q-loss and demo loss.
tensorforce/models/q_demo_model.py
def tf_combined_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): """ Combines Q-loss and demo loss. """ q_model_loss = self.fn_loss( states=states, internals=internals, actions=actions, terminal=terminal, reward=reward, next_states=next_states, next_internals=next_internals, update=update, reference=reference ) demo_loss = self.fn_demo_loss( states=states, internals=internals, actions=actions, terminal=terminal, reward=reward, update=update, reference=reference ) return q_model_loss + self.supervised_weight * demo_loss
def tf_combined_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): """ Combines Q-loss and demo loss. """ q_model_loss = self.fn_loss( states=states, internals=internals, actions=actions, terminal=terminal, reward=reward, next_states=next_states, next_internals=next_internals, update=update, reference=reference ) demo_loss = self.fn_demo_loss( states=states, internals=internals, actions=actions, terminal=terminal, reward=reward, update=update, reference=reference ) return q_model_loss + self.supervised_weight * demo_loss
[ "Combines", "Q", "-", "loss", "and", "demo", "loss", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L206-L232
[ "def", "tf_combined_loss", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ",", "next_states", ",", "next_internals", ",", "update", ",", "reference", "=", "None", ")", ":", "q_model_loss", "=", "self", ".", "f...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
QDemoModel.get_variables
Returns the TensorFlow variables used by the model. Returns: List of variables.
tensorforce/models/q_demo_model.py
def get_variables(self, include_submodules=False, include_nontrainable=False): """ Returns the TensorFlow variables used by the model. Returns: List of variables. """ model_variables = super(QDemoModel, self).get_variables( include_submodules=include_submodules, include_nontrainable=include_nontrainable ) if include_nontrainable: demo_memory_variables = self.demo_memory.get_variables() model_variables += demo_memory_variables return model_variables
def get_variables(self, include_submodules=False, include_nontrainable=False): """ Returns the TensorFlow variables used by the model. Returns: List of variables. """ model_variables = super(QDemoModel, self).get_variables( include_submodules=include_submodules, include_nontrainable=include_nontrainable ) if include_nontrainable: demo_memory_variables = self.demo_memory.get_variables() model_variables += demo_memory_variables return model_variables
[ "Returns", "the", "TensorFlow", "variables", "used", "by", "the", "model", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L299-L315
[ "def", "get_variables", "(", "self", ",", "include_submodules", "=", "False", ",", "include_nontrainable", "=", "False", ")", ":", "model_variables", "=", "super", "(", "QDemoModel", ",", "self", ")", ".", "get_variables", "(", "include_submodules", "=", "includ...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
QDemoModel.import_demo_experience
Stores demonstrations in the demo memory.
tensorforce/models/q_demo_model.py
def import_demo_experience(self, states, internals, actions, terminal, reward): """ Stores demonstrations in the demo memory. """ fetches = self.import_demo_experience_output feed_dict = self.get_feed_dict( states=states, internals=internals, actions=actions, terminal=terminal, reward=reward ) self.monitored_session.run(fetches=fetches, feed_dict=feed_dict)
def import_demo_experience(self, states, internals, actions, terminal, reward): """ Stores demonstrations in the demo memory. """ fetches = self.import_demo_experience_output feed_dict = self.get_feed_dict( states=states, internals=internals, actions=actions, terminal=terminal, reward=reward ) self.monitored_session.run(fetches=fetches, feed_dict=feed_dict)
[ "Stores", "demonstrations", "in", "the", "demo", "memory", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L317-L331
[ "def", "import_demo_experience", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ")", ":", "fetches", "=", "self", ".", "import_demo_experience_output", "feed_dict", "=", "self", ".", "get_feed_dict", "(", "states", ...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
QDemoModel.demo_update
Performs a demonstration update by calling the demo optimization operation. Note that the batch data does not have to be fetched from the demo memory as this is now part of the TensorFlow operation of the demo update.
tensorforce/models/q_demo_model.py
def demo_update(self): """ Performs a demonstration update by calling the demo optimization operation. Note that the batch data does not have to be fetched from the demo memory as this is now part of the TensorFlow operation of the demo update. """ fetches = self.demo_optimization_output self.monitored_session.run(fetches=fetches)
def demo_update(self): """ Performs a demonstration update by calling the demo optimization operation. Note that the batch data does not have to be fetched from the demo memory as this is now part of the TensorFlow operation of the demo update. """ fetches = self.demo_optimization_output self.monitored_session.run(fetches=fetches)
[ "Performs", "a", "demonstration", "update", "by", "calling", "the", "demo", "optimization", "operation", ".", "Note", "that", "the", "batch", "data", "does", "not", "have", "to", "be", "fetched", "from", "the", "demo", "memory", "as", "this", "is", "now", ...
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/q_demo_model.py#L333-L341
[ "def", "demo_update", "(", "self", ")", ":", "fetches", "=", "self", ".", "demo_optimization_output", "self", ".", "monitored_session", ".", "run", "(", "fetches", "=", "fetches", ")" ]
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
Solver.from_config
Creates a solver from a specification dict.
tensorforce/core/optimizers/solvers/solver.py
def from_config(config, kwargs=None): """ Creates a solver from a specification dict. """ return util.get_object( obj=config, predefined=tensorforce.core.optimizers.solvers.solvers, kwargs=kwargs )
def from_config(config, kwargs=None): """ Creates a solver from a specification dict. """ return util.get_object( obj=config, predefined=tensorforce.core.optimizers.solvers.solvers, kwargs=kwargs )
[ "Creates", "a", "solver", "from", "a", "specification", "dict", "." ]
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/solvers/solver.py#L48-L56
[ "def", "from_config", "(", "config", ",", "kwargs", "=", "None", ")", ":", "return", "util", ".", "get_object", "(", "obj", "=", "config", ",", "predefined", "=", "tensorforce", ".", "core", ".", "optimizers", ".", "solvers", ".", "solvers", ",", "kwargs...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
TFOptimizer.tf_step
Keyword Args: arguments: Dict of arguments for passing to fn_loss as **kwargs. fn_loss: A callable taking arguments as kwargs and returning the loss op of the current model.
tensorforce/core/optimizers/tf_optimizer.py
def tf_step(self, time, variables, **kwargs): """ Keyword Args: arguments: Dict of arguments for passing to fn_loss as **kwargs. fn_loss: A callable taking arguments as kwargs and returning the loss op of the current model. """ arguments = kwargs["arguments"] fn_loss = kwargs["fn_loss"] loss = fn_loss(**arguments) # Force loss value to be calculated. with tf.control_dependencies(control_inputs=(loss,)): # Trivial operation to enforce control dependency previous_variables = [variable + 0.0 for variable in variables] # The actual tensorflow minimize op. with tf.control_dependencies(control_inputs=previous_variables): applied = self.tf_optimizer.minimize(loss=loss, var_list=variables) # colocate_gradients_with_ops=True # Return deltas after actually having change the variables. with tf.control_dependencies(control_inputs=(applied,)): return [ variable - previous_variable for variable, previous_variable in zip(variables, previous_variables) ]
def tf_step(self, time, variables, **kwargs): """ Keyword Args: arguments: Dict of arguments for passing to fn_loss as **kwargs. fn_loss: A callable taking arguments as kwargs and returning the loss op of the current model. """ arguments = kwargs["arguments"] fn_loss = kwargs["fn_loss"] loss = fn_loss(**arguments) # Force loss value to be calculated. with tf.control_dependencies(control_inputs=(loss,)): # Trivial operation to enforce control dependency previous_variables = [variable + 0.0 for variable in variables] # The actual tensorflow minimize op. with tf.control_dependencies(control_inputs=previous_variables): applied = self.tf_optimizer.minimize(loss=loss, var_list=variables) # colocate_gradients_with_ops=True # Return deltas after actually having change the variables. with tf.control_dependencies(control_inputs=(applied,)): return [ variable - previous_variable for variable, previous_variable in zip(variables, previous_variables) ]
[ "Keyword", "Args", ":", "arguments", ":", "Dict", "of", "arguments", "for", "passing", "to", "fn_loss", "as", "**", "kwargs", ".", "fn_loss", ":", "A", "callable", "taking", "arguments", "as", "kwargs", "and", "returning", "the", "loss", "op", "of", "the",...
tensorforce/tensorforce
python
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/tf_optimizer.py#L53-L77
[ "def", "tf_step", "(", "self", ",", "time", ",", "variables", ",", "*", "*", "kwargs", ")", ":", "arguments", "=", "kwargs", "[", "\"arguments\"", "]", "fn_loss", "=", "kwargs", "[", "\"fn_loss\"", "]", "loss", "=", "fn_loss", "(", "*", "*", "arguments...
520a8d992230e382f08e315ede5fc477f5e26bfb
valid
SetClipboardText
Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def SetClipboardText(text: str) -> bool: """ Return bool, True if succeed otherwise False. """ if ctypes.windll.user32.OpenClipboard(0): ctypes.windll.user32.EmptyClipboard() textByteLen = (len(text) + 1) * 2 hClipboardData = ctypes.windll.kernel32.GlobalAlloc(0, textByteLen) # GMEM_FIXED=0 hDestText = ctypes.windll.kernel32.GlobalLock(hClipboardData) ctypes.cdll.msvcrt.wcsncpy(ctypes.c_wchar_p(hDestText), ctypes.c_wchar_p(text), textByteLen // 2) ctypes.windll.kernel32.GlobalUnlock(hClipboardData) # system owns hClipboardData after calling SetClipboardData, # application can not write to or free the data once ownership has been transferred to the system ctypes.windll.user32.SetClipboardData(13, hClipboardData) # CF_TEXT=1, CF_UNICODETEXT=13 ctypes.windll.user32.CloseClipboard() return True return False
def SetClipboardText(text: str) -> bool: """ Return bool, True if succeed otherwise False. """ if ctypes.windll.user32.OpenClipboard(0): ctypes.windll.user32.EmptyClipboard() textByteLen = (len(text) + 1) * 2 hClipboardData = ctypes.windll.kernel32.GlobalAlloc(0, textByteLen) # GMEM_FIXED=0 hDestText = ctypes.windll.kernel32.GlobalLock(hClipboardData) ctypes.cdll.msvcrt.wcsncpy(ctypes.c_wchar_p(hDestText), ctypes.c_wchar_p(text), textByteLen // 2) ctypes.windll.kernel32.GlobalUnlock(hClipboardData) # system owns hClipboardData after calling SetClipboardData, # application can not write to or free the data once ownership has been transferred to the system ctypes.windll.user32.SetClipboardData(13, hClipboardData) # CF_TEXT=1, CF_UNICODETEXT=13 ctypes.windll.user32.CloseClipboard() return True return False
[ "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1724-L1740
[ "def", "SetClipboardText", "(", "text", ":", "str", ")", "->", "bool", ":", "if", "ctypes", ".", "windll", ".", "user32", ".", "OpenClipboard", "(", "0", ")", ":", "ctypes", ".", "windll", ".", "user32", ".", "EmptyClipboard", "(", ")", "textByteLen", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SetConsoleColor
Change the text color on console window. color: int, a value in class `ConsoleColor`. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def SetConsoleColor(color: int) -> bool: """ Change the text color on console window. color: int, a value in class `ConsoleColor`. Return bool, True if succeed otherwise False. """ global _ConsoleOutputHandle global _DefaultConsoleColor if not _DefaultConsoleColor: if not _ConsoleOutputHandle: _ConsoleOutputHandle = ctypes.windll.kernel32.GetStdHandle(_StdOutputHandle) bufferInfo = ConsoleScreenBufferInfo() ctypes.windll.kernel32.GetConsoleScreenBufferInfo(_ConsoleOutputHandle, ctypes.byref(bufferInfo)) _DefaultConsoleColor = int(bufferInfo.wAttributes & 0xFF) if sys.stdout: sys.stdout.flush() bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, color))
def SetConsoleColor(color: int) -> bool: """ Change the text color on console window. color: int, a value in class `ConsoleColor`. Return bool, True if succeed otherwise False. """ global _ConsoleOutputHandle global _DefaultConsoleColor if not _DefaultConsoleColor: if not _ConsoleOutputHandle: _ConsoleOutputHandle = ctypes.windll.kernel32.GetStdHandle(_StdOutputHandle) bufferInfo = ConsoleScreenBufferInfo() ctypes.windll.kernel32.GetConsoleScreenBufferInfo(_ConsoleOutputHandle, ctypes.byref(bufferInfo)) _DefaultConsoleColor = int(bufferInfo.wAttributes & 0xFF) if sys.stdout: sys.stdout.flush() bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, color))
[ "Change", "the", "text", "color", "on", "console", "window", ".", "color", ":", "int", "a", "value", "in", "class", "ConsoleColor", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1743-L1759
[ "def", "SetConsoleColor", "(", "color", ":", "int", ")", "->", "bool", ":", "global", "_ConsoleOutputHandle", "global", "_DefaultConsoleColor", "if", "not", "_DefaultConsoleColor", ":", "if", "not", "_ConsoleOutputHandle", ":", "_ConsoleOutputHandle", "=", "ctypes", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
ResetConsoleColor
Reset to the default text color on console window. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def ResetConsoleColor() -> bool: """ Reset to the default text color on console window. Return bool, True if succeed otherwise False. """ if sys.stdout: sys.stdout.flush() bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))
def ResetConsoleColor() -> bool: """ Reset to the default text color on console window. Return bool, True if succeed otherwise False. """ if sys.stdout: sys.stdout.flush() bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))
[ "Reset", "to", "the", "default", "text", "color", "on", "console", "window", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1762-L1769
[ "def", "ResetConsoleColor", "(", ")", "->", "bool", ":", "if", "sys", ".", "stdout", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "bool", "(", "ctypes", ".", "windll", ".", "kernel32", ".", "SetConsoleTextAttribute", "(", "_ConsoleOutputHandle", ",",...
2cc91060982cc8b777152e698d677cc2989bf263
valid
WindowFromPoint
WindowFromPoint from Win32. Return int, a native window handle.
uiautomation/uiautomation.py
def WindowFromPoint(x: int, y: int) -> int: """ WindowFromPoint from Win32. Return int, a native window handle. """ return ctypes.windll.user32.WindowFromPoint(ctypes.wintypes.POINT(x, y))
def WindowFromPoint(x: int, y: int) -> int: """ WindowFromPoint from Win32. Return int, a native window handle. """ return ctypes.windll.user32.WindowFromPoint(ctypes.wintypes.POINT(x, y))
[ "WindowFromPoint", "from", "Win32", ".", "Return", "int", "a", "native", "window", "handle", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1772-L1777
[ "def", "WindowFromPoint", "(", "x", ":", "int", ",", "y", ":", "int", ")", "->", "int", ":", "return", "ctypes", ".", "windll", ".", "user32", ".", "WindowFromPoint", "(", "ctypes", ".", "wintypes", ".", "POINT", "(", "x", ",", "y", ")", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
GetCursorPos
GetCursorPos from Win32. Get current mouse cursor positon. Return tuple, two ints tuple (x, y).
uiautomation/uiautomation.py
def GetCursorPos() -> tuple: """ GetCursorPos from Win32. Get current mouse cursor positon. Return tuple, two ints tuple (x, y). """ point = ctypes.wintypes.POINT(0, 0) ctypes.windll.user32.GetCursorPos(ctypes.byref(point)) return point.x, point.y
def GetCursorPos() -> tuple: """ GetCursorPos from Win32. Get current mouse cursor positon. Return tuple, two ints tuple (x, y). """ point = ctypes.wintypes.POINT(0, 0) ctypes.windll.user32.GetCursorPos(ctypes.byref(point)) return point.x, point.y
[ "GetCursorPos", "from", "Win32", ".", "Get", "current", "mouse", "cursor", "positon", ".", "Return", "tuple", "two", "ints", "tuple", "(", "x", "y", ")", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1780-L1788
[ "def", "GetCursorPos", "(", ")", "->", "tuple", ":", "point", "=", "ctypes", ".", "wintypes", ".", "POINT", "(", "0", ",", "0", ")", "ctypes", ".", "windll", ".", "user32", ".", "GetCursorPos", "(", "ctypes", ".", "byref", "(", "point", ")", ")", "...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SetCursorPos
SetCursorPos from Win32. Set mouse cursor to point x, y. x: int. y: int. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def SetCursorPos(x: int, y: int) -> bool: """ SetCursorPos from Win32. Set mouse cursor to point x, y. x: int. y: int. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.SetCursorPos(x, y))
def SetCursorPos(x: int, y: int) -> bool: """ SetCursorPos from Win32. Set mouse cursor to point x, y. x: int. y: int. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.SetCursorPos(x, y))
[ "SetCursorPos", "from", "Win32", ".", "Set", "mouse", "cursor", "to", "point", "x", "y", ".", "x", ":", "int", ".", "y", ":", "int", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1791-L1799
[ "def", "SetCursorPos", "(", "x", ":", "int", ",", "y", ":", "int", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "user32", ".", "SetCursorPos", "(", "x", ",", "y", ")", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
mouse_event
mouse_event from Win32.
uiautomation/uiautomation.py
def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None: """mouse_event from Win32.""" ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)
def mouse_event(dwFlags: int, dx: int, dy: int, dwData: int, dwExtraInfo: int) -> None: """mouse_event from Win32.""" ctypes.windll.user32.mouse_event(dwFlags, dx, dy, dwData, dwExtraInfo)
[ "mouse_event", "from", "Win32", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1810-L1812
[ "def", "mouse_event", "(", "dwFlags", ":", "int", ",", "dx", ":", "int", ",", "dy", ":", "int", ",", "dwData", ":", "int", ",", "dwExtraInfo", ":", "int", ")", "->", "None", ":", "ctypes", ".", "windll", ".", "user32", ".", "mouse_event", "(", "dwF...
2cc91060982cc8b777152e698d677cc2989bf263
valid
keybd_event
keybd_event from Win32.
uiautomation/uiautomation.py
def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None: """keybd_event from Win32.""" ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo)
def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None: """keybd_event from Win32.""" ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo)
[ "keybd_event", "from", "Win32", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1815-L1817
[ "def", "keybd_event", "(", "bVk", ":", "int", ",", "bScan", ":", "int", ",", "dwFlags", ":", "int", ",", "dwExtraInfo", ":", "int", ")", "->", "None", ":", "ctypes", ".", "windll", ".", "user32", ".", "keybd_event", "(", "bVk", ",", "bScan", ",", "...
2cc91060982cc8b777152e698d677cc2989bf263
valid
PostMessage
PostMessage from Win32. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def PostMessage(handle: int, msg: int, wParam: int, lParam: int) -> bool: """ PostMessage from Win32. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.PostMessageW(ctypes.c_void_p(handle), msg, wParam, lParam))
def PostMessage(handle: int, msg: int, wParam: int, lParam: int) -> bool: """ PostMessage from Win32. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.PostMessageW(ctypes.c_void_p(handle), msg, wParam, lParam))
[ "PostMessage", "from", "Win32", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1820-L1825
[ "def", "PostMessage", "(", "handle", ":", "int", ",", "msg", ":", "int", ",", "wParam", ":", "int", ",", "lParam", ":", "int", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "user32", ".", "PostMessageW", "(", "ctypes", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SendMessage
SendMessage from Win32. Return int, the return value specifies the result of the message processing; it depends on the message sent.
uiautomation/uiautomation.py
def SendMessage(handle: int, msg: int, wParam: int, lParam: int) -> int: """ SendMessage from Win32. Return int, the return value specifies the result of the message processing; it depends on the message sent. """ return ctypes.windll.user32.SendMessageW(ctypes.c_void_p(handle), msg, wParam, lParam)
def SendMessage(handle: int, msg: int, wParam: int, lParam: int) -> int: """ SendMessage from Win32. Return int, the return value specifies the result of the message processing; it depends on the message sent. """ return ctypes.windll.user32.SendMessageW(ctypes.c_void_p(handle), msg, wParam, lParam)
[ "SendMessage", "from", "Win32", ".", "Return", "int", "the", "return", "value", "specifies", "the", "result", "of", "the", "message", "processing", ";", "it", "depends", "on", "the", "message", "sent", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1828-L1834
[ "def", "SendMessage", "(", "handle", ":", "int", ",", "msg", ":", "int", ",", "wParam", ":", "int", ",", "lParam", ":", "int", ")", "->", "int", ":", "return", "ctypes", ".", "windll", ".", "user32", ".", "SendMessageW", "(", "ctypes", ".", "c_void_p...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Click
Simulate mouse click at point x, y. x: int. y: int. waitTime: float.
uiautomation/uiautomation.py
def Click(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(0.05) mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
def Click(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(0.05) mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
[ "Simulate", "mouse", "click", "at", "point", "x", "y", ".", "x", ":", "int", ".", "y", ":", "int", ".", "waitTime", ":", "float", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1837-L1849
[ "def", "Click", "(", "x", ":", "int", ",", "y", ":", "int", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "SetCursorPos", "(", "x", ",", "y", ")", "screenWidth", ",", "screenHeight", "=", "GetScreenSize", "(", ")", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
MiddleClick
Simulate mouse middle click at point x, y. x: int. y: int. waitTime: float.
uiautomation/uiautomation.py
def MiddleClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse middle click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.MiddleDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(0.05) mouse_event(MouseEventFlag.MiddleUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
def MiddleClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse middle click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.MiddleDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(0.05) mouse_event(MouseEventFlag.MiddleUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
[ "Simulate", "mouse", "middle", "click", "at", "point", "x", "y", ".", "x", ":", "int", ".", "y", ":", "int", ".", "waitTime", ":", "float", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1852-L1864
[ "def", "MiddleClick", "(", "x", ":", "int", ",", "y", ":", "int", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "SetCursorPos", "(", "x", ",", "y", ")", "screenWidth", ",", "screenHeight", "=", "GetScreenSize", "(", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
RightClick
Simulate mouse right click at point x, y. x: int. y: int. waitTime: float.
uiautomation/uiautomation.py
def RightClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse right click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(0.05) mouse_event(MouseEventFlag.RightUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
def RightClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse right click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(0.05) mouse_event(MouseEventFlag.RightUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
[ "Simulate", "mouse", "right", "click", "at", "point", "x", "y", ".", "x", ":", "int", ".", "y", ":", "int", ".", "waitTime", ":", "float", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1867-L1879
[ "def", "RightClick", "(", "x", ":", "int", ",", "y", ":", "int", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "SetCursorPos", "(", "x", ",", "y", ")", "screenWidth", ",", "screenHeight", "=", "GetScreenSize", "(", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
PressMouse
Press left mouse. x: int. y: int. waitTime: float.
uiautomation/uiautomation.py
def PressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Press left mouse. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
def PressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Press left mouse. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
[ "Press", "left", "mouse", ".", "x", ":", "int", ".", "y", ":", "int", ".", "waitTime", ":", "float", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1882-L1892
[ "def", "PressMouse", "(", "x", ":", "int", ",", "y", ":", "int", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "SetCursorPos", "(", "x", ",", "y", ")", "screenWidth", ",", "screenHeight", "=", "GetScreenSize", "(", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
ReleaseMouse
Release left mouse. waitTime: float.
uiautomation/uiautomation.py
def ReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None: """ Release left mouse. waitTime: float. """ x, y = GetCursorPos() screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
def ReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None: """ Release left mouse. waitTime: float. """ x, y = GetCursorPos() screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
[ "Release", "left", "mouse", ".", "waitTime", ":", "float", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1895-L1903
[ "def", "ReleaseMouse", "(", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "x", ",", "y", "=", "GetCursorPos", "(", ")", "screenWidth", ",", "screenHeight", "=", "GetScreenSize", "(", ")", "mouse_event", "(", "MouseEventFlag", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
RightPressMouse
Press right mouse. x: int. y: int. waitTime: float.
uiautomation/uiautomation.py
def RightPressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Press right mouse. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
def RightPressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Press right mouse. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
[ "Press", "right", "mouse", ".", "x", ":", "int", ".", "y", ":", "int", ".", "waitTime", ":", "float", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1906-L1916
[ "def", "RightPressMouse", "(", "x", ":", "int", ",", "y", ":", "int", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "SetCursorPos", "(", "x", ",", "y", ")", "screenWidth", ",", "screenHeight", "=", "GetScreenSize", "(...
2cc91060982cc8b777152e698d677cc2989bf263
valid
RightReleaseMouse
Release right mouse. waitTime: float.
uiautomation/uiautomation.py
def RightReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None: """ Release right mouse. waitTime: float. """ x, y = GetCursorPos() screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
def RightReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None: """ Release right mouse. waitTime: float. """ x, y = GetCursorPos() screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
[ "Release", "right", "mouse", ".", "waitTime", ":", "float", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1919-L1927
[ "def", "RightReleaseMouse", "(", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "x", ",", "y", "=", "GetCursorPos", "(", ")", "screenWidth", ",", "screenHeight", "=", "GetScreenSize", "(", ")", "mouse_event", "(", "MouseEventFlag...
2cc91060982cc8b777152e698d677cc2989bf263
valid
MoveTo
Simulate mouse move to point x, y from current cursor. x: int. y: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float.
uiautomation/uiautomation.py
def MoveTo(x: int, y: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse move to point x, y from current cursor. x: int. y: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ if moveSpeed <= 0: moveTime = 0 else: moveTime = MAX_MOVE_SECOND / moveSpeed curX, curY = GetCursorPos() xCount = abs(x - curX) yCount = abs(y - curY) maxPoint = max(xCount, yCount) screenWidth, screenHeight = GetScreenSize() maxSide = max(screenWidth, screenHeight) minSide = min(screenWidth, screenHeight) if maxPoint > minSide: maxPoint = minSide if maxPoint < maxSide: maxPoint = 100 + int((maxSide - 100) / maxSide * maxPoint) moveTime = moveTime * maxPoint * 1.0 / maxSide stepCount = maxPoint // 20 if stepCount > 1: xStep = (x - curX) * 1.0 / stepCount yStep = (y - curY) * 1.0 / stepCount interval = moveTime / stepCount for i in range(stepCount): cx = curX + int(xStep * i) cy = curY + int(yStep * i) # upper-left(0,0), lower-right(65536,65536) # mouse_event(MouseEventFlag.Move | MouseEventFlag.Absolute, cx*65536//screenWidth, cy*65536//screenHeight, 0, 0) SetCursorPos(cx, cy) time.sleep(interval) SetCursorPos(x, y) time.sleep(waitTime)
def MoveTo(x: int, y: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse move to point x, y from current cursor. x: int. y: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ if moveSpeed <= 0: moveTime = 0 else: moveTime = MAX_MOVE_SECOND / moveSpeed curX, curY = GetCursorPos() xCount = abs(x - curX) yCount = abs(y - curY) maxPoint = max(xCount, yCount) screenWidth, screenHeight = GetScreenSize() maxSide = max(screenWidth, screenHeight) minSide = min(screenWidth, screenHeight) if maxPoint > minSide: maxPoint = minSide if maxPoint < maxSide: maxPoint = 100 + int((maxSide - 100) / maxSide * maxPoint) moveTime = moveTime * maxPoint * 1.0 / maxSide stepCount = maxPoint // 20 if stepCount > 1: xStep = (x - curX) * 1.0 / stepCount yStep = (y - curY) * 1.0 / stepCount interval = moveTime / stepCount for i in range(stepCount): cx = curX + int(xStep * i) cy = curY + int(yStep * i) # upper-left(0,0), lower-right(65536,65536) # mouse_event(MouseEventFlag.Move | MouseEventFlag.Absolute, cx*65536//screenWidth, cy*65536//screenHeight, 0, 0) SetCursorPos(cx, cy) time.sleep(interval) SetCursorPos(x, y) time.sleep(waitTime)
[ "Simulate", "mouse", "move", "to", "point", "x", "y", "from", "current", "cursor", ".", "x", ":", "int", ".", "y", ":", "int", ".", "moveSpeed", ":", "float", "1", "normal", "speed", "<", "1", "move", "slower", ">", "1", "move", "faster", ".", "wai...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1930-L1967
[ "def", "MoveTo", "(", "x", ":", "int", ",", "y", ":", "int", ",", "moveSpeed", ":", "float", "=", "1", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "if", "moveSpeed", "<=", "0", ":", "moveTime", "=", "0", "else...
2cc91060982cc8b777152e698d677cc2989bf263
valid
DragDrop
Simulate mouse left button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float.
uiautomation/uiautomation.py
def DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse left button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ PressMouse(x1, y1, 0.05) MoveTo(x2, y2, moveSpeed, 0.05) ReleaseMouse(waitTime)
def DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse left button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ PressMouse(x1, y1, 0.05) MoveTo(x2, y2, moveSpeed, 0.05) ReleaseMouse(waitTime)
[ "Simulate", "mouse", "left", "button", "drag", "from", "point", "x1", "y1", "drop", "to", "point", "x2", "y2", ".", "x1", ":", "int", ".", "y1", ":", "int", ".", "x2", ":", "int", ".", "y2", ":", "int", ".", "moveSpeed", ":", "float", "1", "norma...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1970-L1982
[ "def", "DragDrop", "(", "x1", ":", "int", ",", "y1", ":", "int", ",", "x2", ":", "int", ",", "y2", ":", "int", ",", "moveSpeed", ":", "float", "=", "1", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "PressMouse"...
2cc91060982cc8b777152e698d677cc2989bf263
valid
RightDragDrop
Simulate mouse right button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float.
uiautomation/uiautomation.py
def RightDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse right button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ RightPressMouse(x1, y1, 0.05) MoveTo(x2, y2, moveSpeed, 0.05) RightReleaseMouse(waitTime)
def RightDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse right button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ RightPressMouse(x1, y1, 0.05) MoveTo(x2, y2, moveSpeed, 0.05) RightReleaseMouse(waitTime)
[ "Simulate", "mouse", "right", "button", "drag", "from", "point", "x1", "y1", "drop", "to", "point", "x2", "y2", ".", "x1", ":", "int", ".", "y1", ":", "int", ".", "x2", ":", "int", ".", "y2", ":", "int", ".", "moveSpeed", ":", "float", "1", "norm...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L1985-L1997
[ "def", "RightDragDrop", "(", "x1", ":", "int", ",", "y1", ":", "int", ",", "x2", ":", "int", ",", "y2", ":", "int", ",", "moveSpeed", ":", "float", "=", "1", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "RightP...
2cc91060982cc8b777152e698d677cc2989bf263
valid
WheelUp
Simulate mouse wheel up. wheelTimes: int. interval: float. waitTime: float.
uiautomation/uiautomation.py
def WheelUp(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse wheel up. wheelTimes: int. interval: float. waitTime: float. """ for i in range(wheelTimes): mouse_event(MouseEventFlag.Wheel, 0, 0, 120, 0) #WHEEL_DELTA=120 time.sleep(interval) time.sleep(waitTime)
def WheelUp(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse wheel up. wheelTimes: int. interval: float. waitTime: float. """ for i in range(wheelTimes): mouse_event(MouseEventFlag.Wheel, 0, 0, 120, 0) #WHEEL_DELTA=120 time.sleep(interval) time.sleep(waitTime)
[ "Simulate", "mouse", "wheel", "up", ".", "wheelTimes", ":", "int", ".", "interval", ":", "float", ".", "waitTime", ":", "float", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2013-L2023
[ "def", "WheelUp", "(", "wheelTimes", ":", "int", "=", "1", ",", "interval", ":", "float", "=", "0.05", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "for", "i", "in", "range", "(", "wheelTimes", ")", ":", "mouse_eve...
2cc91060982cc8b777152e698d677cc2989bf263
valid
GetScreenSize
Return tuple, two ints tuple (width, height).
uiautomation/uiautomation.py
def GetScreenSize() -> tuple: """Return tuple, two ints tuple (width, height).""" SM_CXSCREEN = 0 SM_CYSCREEN = 1 w = ctypes.windll.user32.GetSystemMetrics(SM_CXSCREEN) h = ctypes.windll.user32.GetSystemMetrics(SM_CYSCREEN) return w, h
def GetScreenSize() -> tuple: """Return tuple, two ints tuple (width, height).""" SM_CXSCREEN = 0 SM_CYSCREEN = 1 w = ctypes.windll.user32.GetSystemMetrics(SM_CXSCREEN) h = ctypes.windll.user32.GetSystemMetrics(SM_CYSCREEN) return w, h
[ "Return", "tuple", "two", "ints", "tuple", "(", "width", "height", ")", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2026-L2032
[ "def", "GetScreenSize", "(", ")", "->", "tuple", ":", "SM_CXSCREEN", "=", "0", "SM_CYSCREEN", "=", "1", "w", "=", "ctypes", ".", "windll", ".", "user32", ".", "GetSystemMetrics", "(", "SM_CXSCREEN", ")", "h", "=", "ctypes", ".", "windll", ".", "user32", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
GetPixelColor
Get pixel color of a native window. x: int. y: int. handle: int, the handle of a native window. Return int, the bgr value of point (x,y). r = bgr & 0x0000FF g = (bgr & 0x00FF00) >> 8 b = (bgr & 0xFF0000) >> 16 If handle is 0, get pixel from Desktop window(root control). Note: Not all devices support GetPixel. An application should call GetDeviceCaps to determine whether a specified device supports this function. For example, console window doesn't support.
uiautomation/uiautomation.py
def GetPixelColor(x: int, y: int, handle: int = 0) -> int: """ Get pixel color of a native window. x: int. y: int. handle: int, the handle of a native window. Return int, the bgr value of point (x,y). r = bgr & 0x0000FF g = (bgr & 0x00FF00) >> 8 b = (bgr & 0xFF0000) >> 16 If handle is 0, get pixel from Desktop window(root control). Note: Not all devices support GetPixel. An application should call GetDeviceCaps to determine whether a specified device supports this function. For example, console window doesn't support. """ hdc = ctypes.windll.user32.GetWindowDC(ctypes.c_void_p(handle)) bgr = ctypes.windll.gdi32.GetPixel(hdc, x, y) ctypes.windll.user32.ReleaseDC(ctypes.c_void_p(handle), hdc) return bgr
def GetPixelColor(x: int, y: int, handle: int = 0) -> int: """ Get pixel color of a native window. x: int. y: int. handle: int, the handle of a native window. Return int, the bgr value of point (x,y). r = bgr & 0x0000FF g = (bgr & 0x00FF00) >> 8 b = (bgr & 0xFF0000) >> 16 If handle is 0, get pixel from Desktop window(root control). Note: Not all devices support GetPixel. An application should call GetDeviceCaps to determine whether a specified device supports this function. For example, console window doesn't support. """ hdc = ctypes.windll.user32.GetWindowDC(ctypes.c_void_p(handle)) bgr = ctypes.windll.gdi32.GetPixel(hdc, x, y) ctypes.windll.user32.ReleaseDC(ctypes.c_void_p(handle), hdc) return bgr
[ "Get", "pixel", "color", "of", "a", "native", "window", ".", "x", ":", "int", ".", "y", ":", "int", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "Return", "int", "the", "bgr", "value", "of", "point", "(", "x", "...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2035-L2054
[ "def", "GetPixelColor", "(", "x", ":", "int", ",", "y", ":", "int", ",", "handle", ":", "int", "=", "0", ")", "->", "int", ":", "hdc", "=", "ctypes", ".", "windll", ".", "user32", ".", "GetWindowDC", "(", "ctypes", ".", "c_void_p", "(", "handle", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
MessageBox
MessageBox from Win32. content: str. title: str. flags: int, a value or some combined values in class `MB`. Return int, a value in MB whose name starts with Id, such as MB.IdOk
uiautomation/uiautomation.py
def MessageBox(content: str, title: str, flags: int = MB.Ok) -> int: """ MessageBox from Win32. content: str. title: str. flags: int, a value or some combined values in class `MB`. Return int, a value in MB whose name starts with Id, such as MB.IdOk """ return ctypes.windll.user32.MessageBoxW(ctypes.c_void_p(0), ctypes.c_wchar_p(content), ctypes.c_wchar_p(title), flags)
def MessageBox(content: str, title: str, flags: int = MB.Ok) -> int: """ MessageBox from Win32. content: str. title: str. flags: int, a value or some combined values in class `MB`. Return int, a value in MB whose name starts with Id, such as MB.IdOk """ return ctypes.windll.user32.MessageBoxW(ctypes.c_void_p(0), ctypes.c_wchar_p(content), ctypes.c_wchar_p(title), flags)
[ "MessageBox", "from", "Win32", ".", "content", ":", "str", ".", "title", ":", "str", ".", "flags", ":", "int", "a", "value", "or", "some", "combined", "values", "in", "class", "MB", ".", "Return", "int", "a", "value", "in", "MB", "whose", "name", "st...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2057-L2065
[ "def", "MessageBox", "(", "content", ":", "str", ",", "title", ":", "str", ",", "flags", ":", "int", "=", "MB", ".", "Ok", ")", "->", "int", ":", "return", "ctypes", ".", "windll", ".", "user32", ".", "MessageBoxW", "(", "ctypes", ".", "c_void_p", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SetForegroundWindow
SetForegroundWindow from Win32. handle: int, the handle of a native window. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def SetForegroundWindow(handle: int) -> bool: """ SetForegroundWindow from Win32. handle: int, the handle of a native window. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.SetForegroundWindow(ctypes.c_void_p(handle)))
def SetForegroundWindow(handle: int) -> bool: """ SetForegroundWindow from Win32. handle: int, the handle of a native window. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.SetForegroundWindow(ctypes.c_void_p(handle)))
[ "SetForegroundWindow", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2068-L2074
[ "def", "SetForegroundWindow", "(", "handle", ":", "int", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "user32", ".", "SetForegroundWindow", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ")", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
BringWindowToTop
BringWindowToTop from Win32. handle: int, the handle of a native window. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def BringWindowToTop(handle: int) -> bool: """ BringWindowToTop from Win32. handle: int, the handle of a native window. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.BringWindowToTop(ctypes.c_void_p(handle)))
def BringWindowToTop(handle: int) -> bool: """ BringWindowToTop from Win32. handle: int, the handle of a native window. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.BringWindowToTop(ctypes.c_void_p(handle)))
[ "BringWindowToTop", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2077-L2083
[ "def", "BringWindowToTop", "(", "handle", ":", "int", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "user32", ".", "BringWindowToTop", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ")", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
SwitchToThisWindow
SwitchToThisWindow from Win32. handle: int, the handle of a native window.
uiautomation/uiautomation.py
def SwitchToThisWindow(handle: int) -> None: """ SwitchToThisWindow from Win32. handle: int, the handle of a native window. """ ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), 1)
def SwitchToThisWindow(handle: int) -> None: """ SwitchToThisWindow from Win32. handle: int, the handle of a native window. """ ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), 1)
[ "SwitchToThisWindow", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2086-L2091
[ "def", "SwitchToThisWindow", "(", "handle", ":", "int", ")", "->", "None", ":", "ctypes", ".", "windll", ".", "user32", ".", "SwitchToThisWindow", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ",", "1", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
GetAncestor
GetAncestor from Win32. handle: int, the handle of a native window. index: int, a value in class `GAFlag`. Return int, a native window handle.
uiautomation/uiautomation.py
def GetAncestor(handle: int, flag: int) -> int: """ GetAncestor from Win32. handle: int, the handle of a native window. index: int, a value in class `GAFlag`. Return int, a native window handle. """ return ctypes.windll.user32.GetAncestor(ctypes.c_void_p(handle), flag)
def GetAncestor(handle: int, flag: int) -> int: """ GetAncestor from Win32. handle: int, the handle of a native window. index: int, a value in class `GAFlag`. Return int, a native window handle. """ return ctypes.windll.user32.GetAncestor(ctypes.c_void_p(handle), flag)
[ "GetAncestor", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "index", ":", "int", "a", "value", "in", "class", "GAFlag", ".", "Return", "int", "a", "native", "window", "handle", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2094-L2101
[ "def", "GetAncestor", "(", "handle", ":", "int", ",", "flag", ":", "int", ")", "->", "int", ":", "return", "ctypes", ".", "windll", ".", "user32", ".", "GetAncestor", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ",", "flag", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
IsTopLevelWindow
IsTopLevelWindow from Win32. handle: int, the handle of a native window. Return bool. Only available on Windows 7 or Higher.
uiautomation/uiautomation.py
def IsTopLevelWindow(handle: int) -> bool: """ IsTopLevelWindow from Win32. handle: int, the handle of a native window. Return bool. Only available on Windows 7 or Higher. """ return bool(ctypes.windll.user32.IsTopLevelWindow(ctypes.c_void_p(handle)))
def IsTopLevelWindow(handle: int) -> bool: """ IsTopLevelWindow from Win32. handle: int, the handle of a native window. Return bool. Only available on Windows 7 or Higher. """ return bool(ctypes.windll.user32.IsTopLevelWindow(ctypes.c_void_p(handle)))
[ "IsTopLevelWindow", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "Return", "bool", ".", "Only", "available", "on", "Windows", "7", "or", "Higher", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2104-L2111
[ "def", "IsTopLevelWindow", "(", "handle", ":", "int", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "user32", ".", "IsTopLevelWindow", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ")", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
GetWindowLong
GetWindowLong from Win32. handle: int, the handle of a native window. index: int.
uiautomation/uiautomation.py
def GetWindowLong(handle: int, index: int) -> int: """ GetWindowLong from Win32. handle: int, the handle of a native window. index: int. """ return ctypes.windll.user32.GetWindowLongW(ctypes.c_void_p(handle), index)
def GetWindowLong(handle: int, index: int) -> int: """ GetWindowLong from Win32. handle: int, the handle of a native window. index: int. """ return ctypes.windll.user32.GetWindowLongW(ctypes.c_void_p(handle), index)
[ "GetWindowLong", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "index", ":", "int", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2114-L2120
[ "def", "GetWindowLong", "(", "handle", ":", "int", ",", "index", ":", "int", ")", "->", "int", ":", "return", "ctypes", ".", "windll", ".", "user32", ".", "GetWindowLongW", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ",", "index", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
SetWindowLong
SetWindowLong from Win32. handle: int, the handle of a native window. index: int. value: int. Return int, the previous value before set.
uiautomation/uiautomation.py
def SetWindowLong(handle: int, index: int, value: int) -> int: """ SetWindowLong from Win32. handle: int, the handle of a native window. index: int. value: int. Return int, the previous value before set. """ return ctypes.windll.user32.SetWindowLongW(ctypes.c_void_p(handle), index, value)
def SetWindowLong(handle: int, index: int, value: int) -> int: """ SetWindowLong from Win32. handle: int, the handle of a native window. index: int. value: int. Return int, the previous value before set. """ return ctypes.windll.user32.SetWindowLongW(ctypes.c_void_p(handle), index, value)
[ "SetWindowLong", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "index", ":", "int", ".", "value", ":", "int", ".", "Return", "int", "the", "previous", "value", "before", "set", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2123-L2131
[ "def", "SetWindowLong", "(", "handle", ":", "int", ",", "index", ":", "int", ",", "value", ":", "int", ")", "->", "int", ":", "return", "ctypes", ".", "windll", ".", "user32", ".", "SetWindowLongW", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
IsIconic
IsIconic from Win32. Determine whether a native window is minimized. handle: int, the handle of a native window. Return bool.
uiautomation/uiautomation.py
def IsIconic(handle: int) -> bool: """ IsIconic from Win32. Determine whether a native window is minimized. handle: int, the handle of a native window. Return bool. """ return bool(ctypes.windll.user32.IsIconic(ctypes.c_void_p(handle)))
def IsIconic(handle: int) -> bool: """ IsIconic from Win32. Determine whether a native window is minimized. handle: int, the handle of a native window. Return bool. """ return bool(ctypes.windll.user32.IsIconic(ctypes.c_void_p(handle)))
[ "IsIconic", "from", "Win32", ".", "Determine", "whether", "a", "native", "window", "is", "minimized", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "Return", "bool", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2134-L2141
[ "def", "IsIconic", "(", "handle", ":", "int", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "user32", ".", "IsIconic", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ")", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
IsZoomed
IsZoomed from Win32. Determine whether a native window is maximized. handle: int, the handle of a native window. Return bool.
uiautomation/uiautomation.py
def IsZoomed(handle: int) -> bool: """ IsZoomed from Win32. Determine whether a native window is maximized. handle: int, the handle of a native window. Return bool. """ return bool(ctypes.windll.user32.IsZoomed(ctypes.c_void_p(handle)))
def IsZoomed(handle: int) -> bool: """ IsZoomed from Win32. Determine whether a native window is maximized. handle: int, the handle of a native window. Return bool. """ return bool(ctypes.windll.user32.IsZoomed(ctypes.c_void_p(handle)))
[ "IsZoomed", "from", "Win32", ".", "Determine", "whether", "a", "native", "window", "is", "maximized", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "Return", "bool", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2144-L2151
[ "def", "IsZoomed", "(", "handle", ":", "int", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "user32", ".", "IsZoomed", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ")", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
IsWindowVisible
IsWindowVisible from Win32. handle: int, the handle of a native window. Return bool.
uiautomation/uiautomation.py
def IsWindowVisible(handle: int) -> bool: """ IsWindowVisible from Win32. handle: int, the handle of a native window. Return bool. """ return bool(ctypes.windll.user32.IsWindowVisible(ctypes.c_void_p(handle)))
def IsWindowVisible(handle: int) -> bool: """ IsWindowVisible from Win32. handle: int, the handle of a native window. Return bool. """ return bool(ctypes.windll.user32.IsWindowVisible(ctypes.c_void_p(handle)))
[ "IsWindowVisible", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "Return", "bool", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2154-L2160
[ "def", "IsWindowVisible", "(", "handle", ":", "int", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "user32", ".", "IsWindowVisible", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ")", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
ShowWindow
ShowWindow from Win32. handle: int, the handle of a native window. cmdShow: int, a value in clas `SW`. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def ShowWindow(handle: int, cmdShow: int) -> bool: """ ShowWindow from Win32. handle: int, the handle of a native window. cmdShow: int, a value in clas `SW`. Return bool, True if succeed otherwise False. """ return ctypes.windll.user32.ShowWindow(ctypes.c_void_p(handle), cmdShow)
def ShowWindow(handle: int, cmdShow: int) -> bool: """ ShowWindow from Win32. handle: int, the handle of a native window. cmdShow: int, a value in clas `SW`. Return bool, True if succeed otherwise False. """ return ctypes.windll.user32.ShowWindow(ctypes.c_void_p(handle), cmdShow)
[ "ShowWindow", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "cmdShow", ":", "int", "a", "value", "in", "clas", "SW", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2163-L2170
[ "def", "ShowWindow", "(", "handle", ":", "int", ",", "cmdShow", ":", "int", ")", "->", "bool", ":", "return", "ctypes", ".", "windll", ".", "user32", ".", "ShowWindow", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ",", "cmdShow", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
MoveWindow
MoveWindow from Win32. handle: int, the handle of a native window. x: int. y: int. width: int. height: int. repaint: int, use 1 or 0. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def MoveWindow(handle: int, x: int, y: int, width: int, height: int, repaint: int = 1) -> bool: """ MoveWindow from Win32. handle: int, the handle of a native window. x: int. y: int. width: int. height: int. repaint: int, use 1 or 0. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.MoveWindow(ctypes.c_void_p(handle), x, y, width, height, repaint))
def MoveWindow(handle: int, x: int, y: int, width: int, height: int, repaint: int = 1) -> bool: """ MoveWindow from Win32. handle: int, the handle of a native window. x: int. y: int. width: int. height: int. repaint: int, use 1 or 0. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.MoveWindow(ctypes.c_void_p(handle), x, y, width, height, repaint))
[ "MoveWindow", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "x", ":", "int", ".", "y", ":", "int", ".", "width", ":", "int", ".", "height", ":", "int", ".", "repaint", ":", "int", "use", "1", "or...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2173-L2184
[ "def", "MoveWindow", "(", "handle", ":", "int", ",", "x", ":", "int", ",", "y", ":", "int", ",", "width", ":", "int", ",", "height", ":", "int", ",", "repaint", ":", "int", "=", "1", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".",...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SetWindowPos
SetWindowPos from Win32. handle: int, the handle of a native window. hWndInsertAfter: int, a value whose name starts with 'HWND' in class SWP. x: int. y: int. width: int. height: int. flags: int, values whose name starts with 'SWP' in class `SWP`. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def SetWindowPos(handle: int, hWndInsertAfter: int, x: int, y: int, width: int, height: int, flags: int) -> bool: """ SetWindowPos from Win32. handle: int, the handle of a native window. hWndInsertAfter: int, a value whose name starts with 'HWND' in class SWP. x: int. y: int. width: int. height: int. flags: int, values whose name starts with 'SWP' in class `SWP`. Return bool, True if succeed otherwise False. """ return ctypes.windll.user32.SetWindowPos(ctypes.c_void_p(handle), ctypes.c_void_p(hWndInsertAfter), x, y, width, height, flags)
def SetWindowPos(handle: int, hWndInsertAfter: int, x: int, y: int, width: int, height: int, flags: int) -> bool: """ SetWindowPos from Win32. handle: int, the handle of a native window. hWndInsertAfter: int, a value whose name starts with 'HWND' in class SWP. x: int. y: int. width: int. height: int. flags: int, values whose name starts with 'SWP' in class `SWP`. Return bool, True if succeed otherwise False. """ return ctypes.windll.user32.SetWindowPos(ctypes.c_void_p(handle), ctypes.c_void_p(hWndInsertAfter), x, y, width, height, flags)
[ "SetWindowPos", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "hWndInsertAfter", ":", "int", "a", "value", "whose", "name", "starts", "with", "HWND", "in", "class", "SWP", ".", "x", ":", "int", ".", "y...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2187-L2199
[ "def", "SetWindowPos", "(", "handle", ":", "int", ",", "hWndInsertAfter", ":", "int", ",", "x", ":", "int", ",", "y", ":", "int", ",", "width", ":", "int", ",", "height", ":", "int", ",", "flags", ":", "int", ")", "->", "bool", ":", "return", "ct...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SetWindowTopmost
handle: int, the handle of a native window. isTopmost: bool Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def SetWindowTopmost(handle: int, isTopmost: bool) -> bool: """ handle: int, the handle of a native window. isTopmost: bool Return bool, True if succeed otherwise False. """ topValue = SWP.HWND_Topmost if isTopmost else SWP.HWND_NoTopmost return bool(SetWindowPos(handle, topValue, 0, 0, 0, 0, SWP.SWP_NoSize | SWP.SWP_NoMove))
def SetWindowTopmost(handle: int, isTopmost: bool) -> bool: """ handle: int, the handle of a native window. isTopmost: bool Return bool, True if succeed otherwise False. """ topValue = SWP.HWND_Topmost if isTopmost else SWP.HWND_NoTopmost return bool(SetWindowPos(handle, topValue, 0, 0, 0, 0, SWP.SWP_NoSize | SWP.SWP_NoMove))
[ "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "isTopmost", ":", "bool", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2202-L2209
[ "def", "SetWindowTopmost", "(", "handle", ":", "int", ",", "isTopmost", ":", "bool", ")", "->", "bool", ":", "topValue", "=", "SWP", ".", "HWND_Topmost", "if", "isTopmost", "else", "SWP", ".", "HWND_NoTopmost", "return", "bool", "(", "SetWindowPos", "(", "...
2cc91060982cc8b777152e698d677cc2989bf263
valid
GetWindowText
GetWindowText from Win32. handle: int, the handle of a native window. Return str.
uiautomation/uiautomation.py
def GetWindowText(handle: int) -> str: """ GetWindowText from Win32. handle: int, the handle of a native window. Return str. """ arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.user32.GetWindowTextW(ctypes.c_void_p(handle), values, MAX_PATH) return values.value
def GetWindowText(handle: int) -> str: """ GetWindowText from Win32. handle: int, the handle of a native window. Return str. """ arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.user32.GetWindowTextW(ctypes.c_void_p(handle), values, MAX_PATH) return values.value
[ "GetWindowText", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "Return", "str", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2212-L2221
[ "def", "GetWindowText", "(", "handle", ":", "int", ")", "->", "str", ":", "arrayType", "=", "ctypes", ".", "c_wchar", "*", "MAX_PATH", "values", "=", "arrayType", "(", ")", "ctypes", ".", "windll", ".", "user32", ".", "GetWindowTextW", "(", "ctypes", "."...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SetWindowText
SetWindowText from Win32. handle: int, the handle of a native window. text: str. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def SetWindowText(handle: int, text: str) -> bool: """ SetWindowText from Win32. handle: int, the handle of a native window. text: str. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.SetWindowTextW(ctypes.c_void_p(handle), ctypes.c_wchar_p(text)))
def SetWindowText(handle: int, text: str) -> bool: """ SetWindowText from Win32. handle: int, the handle of a native window. text: str. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.user32.SetWindowTextW(ctypes.c_void_p(handle), ctypes.c_wchar_p(text)))
[ "SetWindowText", "from", "Win32", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "text", ":", "str", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2224-L2231
[ "def", "SetWindowText", "(", "handle", ":", "int", ",", "text", ":", "str", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "user32", ".", "SetWindowTextW", "(", "ctypes", ".", "c_void_p", "(", "handle", ")", ",", "ctypes",...
2cc91060982cc8b777152e698d677cc2989bf263
valid
GetEditText
Get text of a native Win32 Edit. handle: int, the handle of a native window. Return str.
uiautomation/uiautomation.py
def GetEditText(handle: int) -> str: """ Get text of a native Win32 Edit. handle: int, the handle of a native window. Return str. """ textLen = SendMessage(handle, 0x000E, 0, 0) + 1 #WM_GETTEXTLENGTH arrayType = ctypes.c_wchar * textLen values = arrayType() SendMessage(handle, 0x000D, textLen, values) #WM_GETTEXT return values.value
def GetEditText(handle: int) -> str: """ Get text of a native Win32 Edit. handle: int, the handle of a native window. Return str. """ textLen = SendMessage(handle, 0x000E, 0, 0) + 1 #WM_GETTEXTLENGTH arrayType = ctypes.c_wchar * textLen values = arrayType() SendMessage(handle, 0x000D, textLen, values) #WM_GETTEXT return values.value
[ "Get", "text", "of", "a", "native", "Win32", "Edit", ".", "handle", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "Return", "str", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2234-L2244
[ "def", "GetEditText", "(", "handle", ":", "int", ")", "->", "str", ":", "textLen", "=", "SendMessage", "(", "handle", ",", "0x000E", ",", "0", ",", "0", ")", "+", "1", "#WM_GETTEXTLENGTH", "arrayType", "=", "ctypes", ".", "c_wchar", "*", "textLen", "va...
2cc91060982cc8b777152e698d677cc2989bf263
valid
GetConsoleOriginalTitle
GetConsoleOriginalTitle from Win32. Return str. Only available on Windows Vista or higher.
uiautomation/uiautomation.py
def GetConsoleOriginalTitle() -> str: """ GetConsoleOriginalTitle from Win32. Return str. Only available on Windows Vista or higher. """ if IsNT6orHigher: arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, MAX_PATH) return values.value else: raise RuntimeError('GetConsoleOriginalTitle is not supported on Windows XP or lower.')
def GetConsoleOriginalTitle() -> str: """ GetConsoleOriginalTitle from Win32. Return str. Only available on Windows Vista or higher. """ if IsNT6orHigher: arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, MAX_PATH) return values.value else: raise RuntimeError('GetConsoleOriginalTitle is not supported on Windows XP or lower.')
[ "GetConsoleOriginalTitle", "from", "Win32", ".", "Return", "str", ".", "Only", "available", "on", "Windows", "Vista", "or", "higher", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2247-L2259
[ "def", "GetConsoleOriginalTitle", "(", ")", "->", "str", ":", "if", "IsNT6orHigher", ":", "arrayType", "=", "ctypes", ".", "c_wchar", "*", "MAX_PATH", "values", "=", "arrayType", "(", ")", "ctypes", ".", "windll", ".", "kernel32", ".", "GetConsoleOriginalTitle...
2cc91060982cc8b777152e698d677cc2989bf263
valid
GetConsoleTitle
GetConsoleTitle from Win32. Return str.
uiautomation/uiautomation.py
def GetConsoleTitle() -> str: """ GetConsoleTitle from Win32. Return str. """ arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.kernel32.GetConsoleTitleW(values, MAX_PATH) return values.value
def GetConsoleTitle() -> str: """ GetConsoleTitle from Win32. Return str. """ arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.kernel32.GetConsoleTitleW(values, MAX_PATH) return values.value
[ "GetConsoleTitle", "from", "Win32", ".", "Return", "str", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2262-L2270
[ "def", "GetConsoleTitle", "(", ")", "->", "str", ":", "arrayType", "=", "ctypes", ".", "c_wchar", "*", "MAX_PATH", "values", "=", "arrayType", "(", ")", "ctypes", ".", "windll", ".", "kernel32", ".", "GetConsoleTitleW", "(", "values", ",", "MAX_PATH", ")",...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SetConsoleTitle
SetConsoleTitle from Win32. text: str. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def SetConsoleTitle(text: str) -> bool: """ SetConsoleTitle from Win32. text: str. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(text)))
def SetConsoleTitle(text: str) -> bool: """ SetConsoleTitle from Win32. text: str. Return bool, True if succeed otherwise False. """ return bool(ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(text)))
[ "SetConsoleTitle", "from", "Win32", ".", "text", ":", "str", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2273-L2279
[ "def", "SetConsoleTitle", "(", "text", ":", "str", ")", "->", "bool", ":", "return", "bool", "(", "ctypes", ".", "windll", ".", "kernel32", ".", "SetConsoleTitleW", "(", "ctypes", ".", "c_wchar_p", "(", "text", ")", ")", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
IsDesktopLocked
Check if desktop is locked. Return bool. Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode.
uiautomation/uiautomation.py
def IsDesktopLocked() -> bool: """ Check if desktop is locked. Return bool. Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode. """ isLocked = False desk = ctypes.windll.user32.OpenDesktopW(ctypes.c_wchar_p('Default'), 0, 0, 0x0100) # DESKTOP_SWITCHDESKTOP = 0x0100 if desk: isLocked = not ctypes.windll.user32.SwitchDesktop(desk) ctypes.windll.user32.CloseDesktop(desk) return isLocked
def IsDesktopLocked() -> bool: """ Check if desktop is locked. Return bool. Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode. """ isLocked = False desk = ctypes.windll.user32.OpenDesktopW(ctypes.c_wchar_p('Default'), 0, 0, 0x0100) # DESKTOP_SWITCHDESKTOP = 0x0100 if desk: isLocked = not ctypes.windll.user32.SwitchDesktop(desk) ctypes.windll.user32.CloseDesktop(desk) return isLocked
[ "Check", "if", "desktop", "is", "locked", ".", "Return", "bool", ".", "Desktop", "is", "locked", "if", "press", "Win", "+", "L", "Ctrl", "+", "Alt", "+", "Del", "or", "in", "remote", "desktop", "mode", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2290-L2301
[ "def", "IsDesktopLocked", "(", ")", "->", "bool", ":", "isLocked", "=", "False", "desk", "=", "ctypes", ".", "windll", ".", "user32", ".", "OpenDesktopW", "(", "ctypes", ".", "c_wchar_p", "(", "'Default'", ")", ",", "0", ",", "0", ",", "0x0100", ")", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
PlayWaveFile
Call PlaySound from Win32. filePath: str, if emtpy, stop playing the current sound. isAsync: bool, if True, the sound is played asynchronously and returns immediately. isLoop: bool, if True, the sound plays repeatedly until PlayWaveFile(None) is called again, must also set isAsync to True. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def PlayWaveFile(filePath: str = r'C:\Windows\Media\notify.wav', isAsync: bool = False, isLoop: bool = False) -> bool: """ Call PlaySound from Win32. filePath: str, if emtpy, stop playing the current sound. isAsync: bool, if True, the sound is played asynchronously and returns immediately. isLoop: bool, if True, the sound plays repeatedly until PlayWaveFile(None) is called again, must also set isAsync to True. Return bool, True if succeed otherwise False. """ if filePath: SND_ASYNC = 0x0001 SND_NODEFAULT = 0x0002 SND_LOOP = 0x0008 SND_FILENAME = 0x20000 flags = SND_NODEFAULT | SND_FILENAME if isAsync: flags |= SND_ASYNC if isLoop: flags |= SND_LOOP flags |= SND_ASYNC return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(filePath), ctypes.c_void_p(0), flags)) else: return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(0), ctypes.c_void_p(0), 0))
def PlayWaveFile(filePath: str = r'C:\Windows\Media\notify.wav', isAsync: bool = False, isLoop: bool = False) -> bool: """ Call PlaySound from Win32. filePath: str, if emtpy, stop playing the current sound. isAsync: bool, if True, the sound is played asynchronously and returns immediately. isLoop: bool, if True, the sound plays repeatedly until PlayWaveFile(None) is called again, must also set isAsync to True. Return bool, True if succeed otherwise False. """ if filePath: SND_ASYNC = 0x0001 SND_NODEFAULT = 0x0002 SND_LOOP = 0x0008 SND_FILENAME = 0x20000 flags = SND_NODEFAULT | SND_FILENAME if isAsync: flags |= SND_ASYNC if isLoop: flags |= SND_LOOP flags |= SND_ASYNC return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(filePath), ctypes.c_void_p(0), flags)) else: return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(0), ctypes.c_void_p(0), 0))
[ "Call", "PlaySound", "from", "Win32", ".", "filePath", ":", "str", "if", "emtpy", "stop", "playing", "the", "current", "sound", ".", "isAsync", ":", "bool", "if", "True", "the", "sound", "is", "played", "asynchronously", "and", "returns", "immediately", ".",...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2304-L2325
[ "def", "PlayWaveFile", "(", "filePath", ":", "str", "=", "r'C:\\Windows\\Media\\notify.wav'", ",", "isAsync", ":", "bool", "=", "False", ",", "isLoop", ":", "bool", "=", "False", ")", "->", "bool", ":", "if", "filePath", ":", "SND_ASYNC", "=", "0x0001", "S...
2cc91060982cc8b777152e698d677cc2989bf263
valid
IsProcess64Bit
Return True if process is 64 bit. Return False if process is 32 bit. Return None if unknown, maybe caused by having no acess right to the process.
uiautomation/uiautomation.py
def IsProcess64Bit(processId: int) -> bool: """ Return True if process is 64 bit. Return False if process is 32 bit. Return None if unknown, maybe caused by having no acess right to the process. """ try: func = ctypes.windll.ntdll.ZwWow64ReadVirtualMemory64 #only 64 bit OS has this function except Exception as ex: return False try: IsWow64Process = ctypes.windll.kernel32.IsWow64Process IsWow64Process.argtypes = (ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)) except Exception as ex: return False hProcess = ctypes.windll.kernel32.OpenProcess(0x1000, 0, processId) #PROCESS_QUERY_INFORMATION=0x0400,PROCESS_QUERY_LIMITED_INFORMATION=0x1000 if hProcess: is64Bit = ctypes.c_int32() if IsWow64Process(hProcess, ctypes.byref(is64Bit)): ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hProcess)) return False if is64Bit.value else True else: ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hProcess))
def IsProcess64Bit(processId: int) -> bool: """ Return True if process is 64 bit. Return False if process is 32 bit. Return None if unknown, maybe caused by having no acess right to the process. """ try: func = ctypes.windll.ntdll.ZwWow64ReadVirtualMemory64 #only 64 bit OS has this function except Exception as ex: return False try: IsWow64Process = ctypes.windll.kernel32.IsWow64Process IsWow64Process.argtypes = (ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)) except Exception as ex: return False hProcess = ctypes.windll.kernel32.OpenProcess(0x1000, 0, processId) #PROCESS_QUERY_INFORMATION=0x0400,PROCESS_QUERY_LIMITED_INFORMATION=0x1000 if hProcess: is64Bit = ctypes.c_int32() if IsWow64Process(hProcess, ctypes.byref(is64Bit)): ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hProcess)) return False if is64Bit.value else True else: ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hProcess))
[ "Return", "True", "if", "process", "is", "64", "bit", ".", "Return", "False", "if", "process", "is", "32", "bit", ".", "Return", "None", "if", "unknown", "maybe", "caused", "by", "having", "no", "acess", "right", "to", "the", "process", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2328-L2350
[ "def", "IsProcess64Bit", "(", "processId", ":", "int", ")", "->", "bool", ":", "try", ":", "func", "=", "ctypes", ".", "windll", ".", "ntdll", ".", "ZwWow64ReadVirtualMemory64", "#only 64 bit OS has this function", "except", "Exception", "as", "ex", ":", "return...
2cc91060982cc8b777152e698d677cc2989bf263
valid
RunScriptAsAdmin
Run a python script as administrator. System will show a popup dialog askes you whether to elevate as administrator if UAC is enabled. argv: list, a str list like sys.argv, argv[0] is the script file, argv[1:] are other arguments. workingDirectory: str, the working directory for the script file. showFlag: int, a value in class `SW`. Return bool, True if succeed.
uiautomation/uiautomation.py
def RunScriptAsAdmin(argv: list, workingDirectory: str = None, showFlag: int = SW.ShowNormal) -> bool: """ Run a python script as administrator. System will show a popup dialog askes you whether to elevate as administrator if UAC is enabled. argv: list, a str list like sys.argv, argv[0] is the script file, argv[1:] are other arguments. workingDirectory: str, the working directory for the script file. showFlag: int, a value in class `SW`. Return bool, True if succeed. """ args = ' '.join('"{}"'.format(arg) for arg in argv) return ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, args, workingDirectory, showFlag) > 32
def RunScriptAsAdmin(argv: list, workingDirectory: str = None, showFlag: int = SW.ShowNormal) -> bool: """ Run a python script as administrator. System will show a popup dialog askes you whether to elevate as administrator if UAC is enabled. argv: list, a str list like sys.argv, argv[0] is the script file, argv[1:] are other arguments. workingDirectory: str, the working directory for the script file. showFlag: int, a value in class `SW`. Return bool, True if succeed. """ args = ' '.join('"{}"'.format(arg) for arg in argv) return ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, args, workingDirectory, showFlag) > 32
[ "Run", "a", "python", "script", "as", "administrator", ".", "System", "will", "show", "a", "popup", "dialog", "askes", "you", "whether", "to", "elevate", "as", "administrator", "if", "UAC", "is", "enabled", ".", "argv", ":", "list", "a", "str", "list", "...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2362-L2372
[ "def", "RunScriptAsAdmin", "(", "argv", ":", "list", ",", "workingDirectory", ":", "str", "=", "None", ",", "showFlag", ":", "int", "=", "SW", ".", "ShowNormal", ")", "->", "bool", ":", "args", "=", "' '", ".", "join", "(", "'\"{}\"'", ".", "format", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SendKey
Simulate typing a key. key: int, a value in class `Keys`.
uiautomation/uiautomation.py
def SendKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate typing a key. key: int, a value in class `Keys`. """ keybd_event(key, 0, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey, 0) keybd_event(key, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
def SendKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate typing a key. key: int, a value in class `Keys`. """ keybd_event(key, 0, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey, 0) keybd_event(key, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
[ "Simulate", "typing", "a", "key", ".", "key", ":", "int", "a", "value", "in", "class", "Keys", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2375-L2382
[ "def", "SendKey", "(", "key", ":", "int", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "keybd_event", "(", "key", ",", "0", ",", "KeyboardEventFlag", ".", "KeyDown", "|", "KeyboardEventFlag", ".", "ExtendedKey", ",", "...
2cc91060982cc8b777152e698d677cc2989bf263
valid
PressKey
Simulate a key down for key. key: int, a value in class `Keys`. waitTime: float.
uiautomation/uiautomation.py
def PressKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate a key down for key. key: int, a value in class `Keys`. waitTime: float. """ keybd_event(key, 0, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
def PressKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate a key down for key. key: int, a value in class `Keys`. waitTime: float. """ keybd_event(key, 0, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
[ "Simulate", "a", "key", "down", "for", "key", ".", "key", ":", "int", "a", "value", "in", "class", "Keys", ".", "waitTime", ":", "float", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2385-L2392
[ "def", "PressKey", "(", "key", ":", "int", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "keybd_event", "(", "key", ",", "0", ",", "KeyboardEventFlag", ".", "KeyDown", "|", "KeyboardEventFlag", ".", "ExtendedKey", ",", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
ReleaseKey
Simulate a key up for key. key: int, a value in class `Keys`. waitTime: float.
uiautomation/uiautomation.py
def ReleaseKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate a key up for key. key: int, a value in class `Keys`. waitTime: float. """ keybd_event(key, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
def ReleaseKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate a key up for key. key: int, a value in class `Keys`. waitTime: float. """ keybd_event(key, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
[ "Simulate", "a", "key", "up", "for", "key", ".", "key", ":", "int", "a", "value", "in", "class", "Keys", ".", "waitTime", ":", "float", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2395-L2402
[ "def", "ReleaseKey", "(", "key", ":", "int", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "keybd_event", "(", "key", ",", "0", ",", "KeyboardEventFlag", ".", "KeyUp", "|", "KeyboardEventFlag", ".", "ExtendedKey", ",", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
IsKeyPressed
key: int, a value in class `Keys`. Return bool.
uiautomation/uiautomation.py
def IsKeyPressed(key: int) -> bool: """ key: int, a value in class `Keys`. Return bool. """ state = ctypes.windll.user32.GetAsyncKeyState(key) return bool(state & 0x8000)
def IsKeyPressed(key: int) -> bool: """ key: int, a value in class `Keys`. Return bool. """ state = ctypes.windll.user32.GetAsyncKeyState(key) return bool(state & 0x8000)
[ "key", ":", "int", "a", "value", "in", "class", "Keys", ".", "Return", "bool", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2405-L2411
[ "def", "IsKeyPressed", "(", "key", ":", "int", ")", "->", "bool", ":", "state", "=", "ctypes", ".", "windll", ".", "user32", ".", "GetAsyncKeyState", "(", "key", ")", "return", "bool", "(", "state", "&", "0x8000", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
_CreateInput
Create Win32 struct `INPUT` for `SendInput`. Return `INPUT`.
uiautomation/uiautomation.py
def _CreateInput(structure) -> INPUT: """ Create Win32 struct `INPUT` for `SendInput`. Return `INPUT`. """ if isinstance(structure, MOUSEINPUT): return INPUT(InputType.Mouse, _INPUTUnion(mi=structure)) if isinstance(structure, KEYBDINPUT): return INPUT(InputType.Keyboard, _INPUTUnion(ki=structure)) if isinstance(structure, HARDWAREINPUT): return INPUT(InputType.Hardware, _INPUTUnion(hi=structure)) raise TypeError('Cannot create INPUT structure!')
def _CreateInput(structure) -> INPUT: """ Create Win32 struct `INPUT` for `SendInput`. Return `INPUT`. """ if isinstance(structure, MOUSEINPUT): return INPUT(InputType.Mouse, _INPUTUnion(mi=structure)) if isinstance(structure, KEYBDINPUT): return INPUT(InputType.Keyboard, _INPUTUnion(ki=structure)) if isinstance(structure, HARDWAREINPUT): return INPUT(InputType.Hardware, _INPUTUnion(hi=structure)) raise TypeError('Cannot create INPUT structure!')
[ "Create", "Win32", "struct", "INPUT", "for", "SendInput", ".", "Return", "INPUT", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2414-L2425
[ "def", "_CreateInput", "(", "structure", ")", "->", "INPUT", ":", "if", "isinstance", "(", "structure", ",", "MOUSEINPUT", ")", ":", "return", "INPUT", "(", "InputType", ".", "Mouse", ",", "_INPUTUnion", "(", "mi", "=", "structure", ")", ")", "if", "isin...
2cc91060982cc8b777152e698d677cc2989bf263
valid
MouseInput
Create Win32 struct `MOUSEINPUT` for `SendInput`. Return `INPUT`.
uiautomation/uiautomation.py
def MouseInput(dx: int, dy: int, mouseData: int = 0, dwFlags: int = MouseEventFlag.LeftDown, time_: int = 0) -> INPUT: """ Create Win32 struct `MOUSEINPUT` for `SendInput`. Return `INPUT`. """ return _CreateInput(MOUSEINPUT(dx, dy, mouseData, dwFlags, time_, None))
def MouseInput(dx: int, dy: int, mouseData: int = 0, dwFlags: int = MouseEventFlag.LeftDown, time_: int = 0) -> INPUT: """ Create Win32 struct `MOUSEINPUT` for `SendInput`. Return `INPUT`. """ return _CreateInput(MOUSEINPUT(dx, dy, mouseData, dwFlags, time_, None))
[ "Create", "Win32", "struct", "MOUSEINPUT", "for", "SendInput", ".", "Return", "INPUT", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2428-L2433
[ "def", "MouseInput", "(", "dx", ":", "int", ",", "dy", ":", "int", ",", "mouseData", ":", "int", "=", "0", ",", "dwFlags", ":", "int", "=", "MouseEventFlag", ".", "LeftDown", ",", "time_", ":", "int", "=", "0", ")", "->", "INPUT", ":", "return", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
KeyboardInput
Create Win32 struct `KEYBDINPUT` for `SendInput`.
uiautomation/uiautomation.py
def KeyboardInput(wVk: int, wScan: int, dwFlags: int = KeyboardEventFlag.KeyDown, time_: int = 0) -> INPUT: """Create Win32 struct `KEYBDINPUT` for `SendInput`.""" return _CreateInput(KEYBDINPUT(wVk, wScan, dwFlags, time_, None))
def KeyboardInput(wVk: int, wScan: int, dwFlags: int = KeyboardEventFlag.KeyDown, time_: int = 0) -> INPUT: """Create Win32 struct `KEYBDINPUT` for `SendInput`.""" return _CreateInput(KEYBDINPUT(wVk, wScan, dwFlags, time_, None))
[ "Create", "Win32", "struct", "KEYBDINPUT", "for", "SendInput", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2436-L2438
[ "def", "KeyboardInput", "(", "wVk", ":", "int", ",", "wScan", ":", "int", ",", "dwFlags", ":", "int", "=", "KeyboardEventFlag", ".", "KeyDown", ",", "time_", ":", "int", "=", "0", ")", "->", "INPUT", ":", "return", "_CreateInput", "(", "KEYBDINPUT", "(...
2cc91060982cc8b777152e698d677cc2989bf263
valid
HardwareInput
Create Win32 struct `HARDWAREINPUT` for `SendInput`.
uiautomation/uiautomation.py
def HardwareInput(uMsg: int, param: int = 0) -> INPUT: """Create Win32 struct `HARDWAREINPUT` for `SendInput`.""" return _CreateInput(HARDWAREINPUT(uMsg, param & 0xFFFF, param >> 16 & 0xFFFF))
def HardwareInput(uMsg: int, param: int = 0) -> INPUT: """Create Win32 struct `HARDWAREINPUT` for `SendInput`.""" return _CreateInput(HARDWAREINPUT(uMsg, param & 0xFFFF, param >> 16 & 0xFFFF))
[ "Create", "Win32", "struct", "HARDWAREINPUT", "for", "SendInput", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2441-L2443
[ "def", "HardwareInput", "(", "uMsg", ":", "int", ",", "param", ":", "int", "=", "0", ")", "->", "INPUT", ":", "return", "_CreateInput", "(", "HARDWAREINPUT", "(", "uMsg", ",", "param", "&", "0xFFFF", ",", "param", ">>", "16", "&", "0xFFFF", ")", ")" ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SendUnicodeChar
Type a single unicode char. char: str, len(char) must equal to 1. Return int, the number of events that it successfully inserted into the keyboard or mouse input stream. If the function returns zero, the input was already blocked by another thread.
uiautomation/uiautomation.py
def SendUnicodeChar(char: str) -> int: """ Type a single unicode char. char: str, len(char) must equal to 1. Return int, the number of events that it successfully inserted into the keyboard or mouse input stream. If the function returns zero, the input was already blocked by another thread. """ return SendInput(KeyboardInput(0, ord(char), KeyboardEventFlag.KeyUnicode | KeyboardEventFlag.KeyDown), KeyboardInput(0, ord(char), KeyboardEventFlag.KeyUnicode | KeyboardEventFlag.KeyUp))
def SendUnicodeChar(char: str) -> int: """ Type a single unicode char. char: str, len(char) must equal to 1. Return int, the number of events that it successfully inserted into the keyboard or mouse input stream. If the function returns zero, the input was already blocked by another thread. """ return SendInput(KeyboardInput(0, ord(char), KeyboardEventFlag.KeyUnicode | KeyboardEventFlag.KeyDown), KeyboardInput(0, ord(char), KeyboardEventFlag.KeyUnicode | KeyboardEventFlag.KeyUp))
[ "Type", "a", "single", "unicode", "char", ".", "char", ":", "str", "len", "(", "char", ")", "must", "equal", "to", "1", ".", "Return", "int", "the", "number", "of", "events", "that", "it", "successfully", "inserted", "into", "the", "keyboard", "or", "m...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2460-L2468
[ "def", "SendUnicodeChar", "(", "char", ":", "str", ")", "->", "int", ":", "return", "SendInput", "(", "KeyboardInput", "(", "0", ",", "ord", "(", "char", ")", ",", "KeyboardEventFlag", ".", "KeyUnicode", "|", "KeyboardEventFlag", ".", "KeyDown", ")", ",", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
_VKtoSC
This function is only for internal use in SendKeys. key: int, a value in class `Keys`. Return int.
uiautomation/uiautomation.py
def _VKtoSC(key: int) -> int: """ This function is only for internal use in SendKeys. key: int, a value in class `Keys`. Return int. """ if key in _SCKeys: return _SCKeys[key] scanCode = ctypes.windll.user32.MapVirtualKeyA(key, 0) if not scanCode: return 0 keyList = [Keys.VK_APPS, Keys.VK_CANCEL, Keys.VK_SNAPSHOT, Keys.VK_DIVIDE, Keys.VK_NUMLOCK] if key in keyList: scanCode |= 0x0100 return scanCode
def _VKtoSC(key: int) -> int: """ This function is only for internal use in SendKeys. key: int, a value in class `Keys`. Return int. """ if key in _SCKeys: return _SCKeys[key] scanCode = ctypes.windll.user32.MapVirtualKeyA(key, 0) if not scanCode: return 0 keyList = [Keys.VK_APPS, Keys.VK_CANCEL, Keys.VK_SNAPSHOT, Keys.VK_DIVIDE, Keys.VK_NUMLOCK] if key in keyList: scanCode |= 0x0100 return scanCode
[ "This", "function", "is", "only", "for", "internal", "use", "in", "SendKeys", ".", "key", ":", "int", "a", "value", "in", "class", "Keys", ".", "Return", "int", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2499-L2513
[ "def", "_VKtoSC", "(", "key", ":", "int", ")", "->", "int", ":", "if", "key", "in", "_SCKeys", ":", "return", "_SCKeys", "[", "key", "]", "scanCode", "=", "ctypes", ".", "windll", ".", "user32", ".", "MapVirtualKeyA", "(", "key", ",", "0", ")", "if...
2cc91060982cc8b777152e698d677cc2989bf263
valid
SendKeys
Simulate typing keys on keyboard. text: str, keys to type. interval: float, seconds between keys. waitTime: float. debug: bool, if True, print the keys. Examples: {Ctrl}, {Delete} ... are special keys' name in SpecialKeyNames. SendKeys('{Ctrl}a{Delete}{Ctrl}v{Ctrl}s{Ctrl}{Shift}s{Win}e{PageDown}') #press Ctrl+a, Delete, Ctrl+v, Ctrl+s, Ctrl+Shift+s, Win+e, PageDown SendKeys('{Ctrl}(AB)({Shift}(123))') #press Ctrl+A+B, type (, press Shift+1+2+3, type ), if () follows a hold key, hold key won't release util ) SendKeys('{Ctrl}{a 3}') #press Ctrl+a at the same time, release Ctrl+a, then type a 2 times SendKeys('{a 3}{B 5}') #type a 3 times, type B 5 times SendKeys('{{}Hello{}}abc {a}{b}{c} test{} 3}{!}{a} (){(}{)}') #type: {Hello}abc abc test}}}!a ()() SendKeys('0123456789{Enter}') SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{Enter}') SendKeys('abcdefghijklmnopqrstuvwxyz{Enter}') SendKeys('`~!@#$%^&*()-_=+{Enter}') SendKeys('[]{{}{}}\\|;:\'\",<.>/?{Enter}')
uiautomation/uiautomation.py
def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT_TIME, debug: bool = False) -> None: """ Simulate typing keys on keyboard. text: str, keys to type. interval: float, seconds between keys. waitTime: float. debug: bool, if True, print the keys. Examples: {Ctrl}, {Delete} ... are special keys' name in SpecialKeyNames. SendKeys('{Ctrl}a{Delete}{Ctrl}v{Ctrl}s{Ctrl}{Shift}s{Win}e{PageDown}') #press Ctrl+a, Delete, Ctrl+v, Ctrl+s, Ctrl+Shift+s, Win+e, PageDown SendKeys('{Ctrl}(AB)({Shift}(123))') #press Ctrl+A+B, type (, press Shift+1+2+3, type ), if () follows a hold key, hold key won't release util ) SendKeys('{Ctrl}{a 3}') #press Ctrl+a at the same time, release Ctrl+a, then type a 2 times SendKeys('{a 3}{B 5}') #type a 3 times, type B 5 times SendKeys('{{}Hello{}}abc {a}{b}{c} test{} 3}{!}{a} (){(}{)}') #type: {Hello}abc abc test}}}!a ()() SendKeys('0123456789{Enter}') SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{Enter}') SendKeys('abcdefghijklmnopqrstuvwxyz{Enter}') SendKeys('`~!@#$%^&*()-_=+{Enter}') SendKeys('[]{{}{}}\\|;:\'\",<.>/?{Enter}') """ holdKeys = ('WIN', 'LWIN', 'RWIN', 'SHIFT', 'LSHIFT', 'RSHIFT', 'CTRL', 'CONTROL', 'LCTRL', 'RCTRL', 'LCONTROL', 'LCONTROL', 'ALT', 'LALT', 'RALT') keys = [] printKeys = [] i = 0 insertIndex = 0 length = len(text) hold = False include = False lastKeyValue = None while True: if text[i] == '{': rindex = text.find('}', i) if rindex == i + 1:#{}} rindex = text.find('}', i + 2) if rindex == -1: raise ValueError('"{" or "{}" is not valid, use "{{}" for "{", use "{}}" for "}"') key = text[i + 1:rindex] key = [it for it in key.split(' ') if it] if not key: raise ValueError('"{}" is not valid, use "{{Space}}" or " " for " "'.format(text[i:rindex + 1])) if (len(key) == 2 and not key[1].isdigit()) or len(key) > 2: raise ValueError('"{}" is not valid'.format(text[i:rindex + 1])) upperKey = key[0].upper() count = 1 if len(key) > 1: count = int(key[1]) for j in range(count): if hold: if upperKey in SpecialKeyNames: keyValue = SpecialKeyNames[upperKey] if type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue: insertIndex += 1 printKeys.insert(insertIndex, (key[0], 'KeyDown | ExtendedKey')) printKeys.insert(insertIndex + 1, (key[0], 'KeyUp | ExtendedKey')) keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue elif key[0] in CharacterCodes: keyValue = CharacterCodes[key[0]] if type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue: insertIndex += 1 printKeys.insert(insertIndex, (key[0], 'KeyDown | ExtendedKey')) printKeys.insert(insertIndex + 1, (key[0], 'KeyUp | ExtendedKey')) keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue else: printKeys.insert(insertIndex, (key[0], 'UnicodeChar')) keys.insert(insertIndex, (key[0], 'UnicodeChar')) lastKeyValue = key[0] if include: insertIndex += 1 else: if upperKey in holdKeys: insertIndex += 1 else: hold = False else: if upperKey in SpecialKeyNames: keyValue = SpecialKeyNames[upperKey] printKeys.append((key[0], 'KeyDown | ExtendedKey')) printKeys.append((key[0], 'KeyUp | ExtendedKey')) keys.append((keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.append((keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue if upperKey in holdKeys: hold = True insertIndex = len(keys) - 1 else: hold = False else: printKeys.append((key[0], 'UnicodeChar')) keys.append((key[0], 'UnicodeChar')) lastKeyValue = key[0] i = rindex + 1 elif text[i] == '(': if hold: include = True else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] i += 1 elif text[i] == ')': if hold: include = False hold = False else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] i += 1 else: if hold: if text[i] in CharacterCodes: keyValue = CharacterCodes[text[i]] if include and type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue: insertIndex += 1 printKeys.insert(insertIndex, (text[i], 'KeyDown | ExtendedKey')) printKeys.insert(insertIndex + 1, (text[i], 'KeyUp | ExtendedKey')) keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] if include: insertIndex += 1 else: hold = False else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] i += 1 if i >= length: break hotkeyInterval = 0.01 for i, key in enumerate(keys): if key[1] == 'UnicodeChar': SendUnicodeChar(key[0]) time.sleep(interval) if debug: Logger.ColorfullyWrite('<Color=DarkGreen>{}</Color>, sleep({})\n'.format(printKeys[i], interval), writeToFile=False) else: scanCode = _VKtoSC(key[0]) keybd_event(key[0], scanCode, key[1], 0) if debug: Logger.Write(printKeys[i], ConsoleColor.DarkGreen, writeToFile=False) if i + 1 == len(keys): time.sleep(interval) if debug: Logger.Write(', sleep({})\n'.format(interval), writeToFile=False) else: if key[1] & KeyboardEventFlag.KeyUp: if keys[i + 1][1] == 'UnicodeChar' or keys[i + 1][1] & KeyboardEventFlag.KeyUp == 0: time.sleep(interval) if debug: Logger.Write(', sleep({})\n'.format(interval), writeToFile=False) else: time.sleep(hotkeyInterval) #must sleep for a while, otherwise combined keys may not be caught if debug: Logger.Write(', sleep({})\n'.format(hotkeyInterval), writeToFile=False) else: #KeyboardEventFlag.KeyDown time.sleep(hotkeyInterval) if debug: Logger.Write(', sleep({})\n'.format(hotkeyInterval), writeToFile=False) #make sure hold keys are not pressed #win = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_LWIN) #ctrl = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_CONTROL) #alt = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_MENU) #shift = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_SHIFT) #if win & 0x8000: #Logger.WriteLine('ERROR: WIN is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_LWIN, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) #if ctrl & 0x8000: #Logger.WriteLine('ERROR: CTRL is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_CONTROL, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) #if alt & 0x8000: #Logger.WriteLine('ERROR: ALT is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_MENU, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) #if shift & 0x8000: #Logger.WriteLine('ERROR: SHIFT is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_SHIFT, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT_TIME, debug: bool = False) -> None: """ Simulate typing keys on keyboard. text: str, keys to type. interval: float, seconds between keys. waitTime: float. debug: bool, if True, print the keys. Examples: {Ctrl}, {Delete} ... are special keys' name in SpecialKeyNames. SendKeys('{Ctrl}a{Delete}{Ctrl}v{Ctrl}s{Ctrl}{Shift}s{Win}e{PageDown}') #press Ctrl+a, Delete, Ctrl+v, Ctrl+s, Ctrl+Shift+s, Win+e, PageDown SendKeys('{Ctrl}(AB)({Shift}(123))') #press Ctrl+A+B, type (, press Shift+1+2+3, type ), if () follows a hold key, hold key won't release util ) SendKeys('{Ctrl}{a 3}') #press Ctrl+a at the same time, release Ctrl+a, then type a 2 times SendKeys('{a 3}{B 5}') #type a 3 times, type B 5 times SendKeys('{{}Hello{}}abc {a}{b}{c} test{} 3}{!}{a} (){(}{)}') #type: {Hello}abc abc test}}}!a ()() SendKeys('0123456789{Enter}') SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{Enter}') SendKeys('abcdefghijklmnopqrstuvwxyz{Enter}') SendKeys('`~!@#$%^&*()-_=+{Enter}') SendKeys('[]{{}{}}\\|;:\'\",<.>/?{Enter}') """ holdKeys = ('WIN', 'LWIN', 'RWIN', 'SHIFT', 'LSHIFT', 'RSHIFT', 'CTRL', 'CONTROL', 'LCTRL', 'RCTRL', 'LCONTROL', 'LCONTROL', 'ALT', 'LALT', 'RALT') keys = [] printKeys = [] i = 0 insertIndex = 0 length = len(text) hold = False include = False lastKeyValue = None while True: if text[i] == '{': rindex = text.find('}', i) if rindex == i + 1:#{}} rindex = text.find('}', i + 2) if rindex == -1: raise ValueError('"{" or "{}" is not valid, use "{{}" for "{", use "{}}" for "}"') key = text[i + 1:rindex] key = [it for it in key.split(' ') if it] if not key: raise ValueError('"{}" is not valid, use "{{Space}}" or " " for " "'.format(text[i:rindex + 1])) if (len(key) == 2 and not key[1].isdigit()) or len(key) > 2: raise ValueError('"{}" is not valid'.format(text[i:rindex + 1])) upperKey = key[0].upper() count = 1 if len(key) > 1: count = int(key[1]) for j in range(count): if hold: if upperKey in SpecialKeyNames: keyValue = SpecialKeyNames[upperKey] if type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue: insertIndex += 1 printKeys.insert(insertIndex, (key[0], 'KeyDown | ExtendedKey')) printKeys.insert(insertIndex + 1, (key[0], 'KeyUp | ExtendedKey')) keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue elif key[0] in CharacterCodes: keyValue = CharacterCodes[key[0]] if type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue: insertIndex += 1 printKeys.insert(insertIndex, (key[0], 'KeyDown | ExtendedKey')) printKeys.insert(insertIndex + 1, (key[0], 'KeyUp | ExtendedKey')) keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue else: printKeys.insert(insertIndex, (key[0], 'UnicodeChar')) keys.insert(insertIndex, (key[0], 'UnicodeChar')) lastKeyValue = key[0] if include: insertIndex += 1 else: if upperKey in holdKeys: insertIndex += 1 else: hold = False else: if upperKey in SpecialKeyNames: keyValue = SpecialKeyNames[upperKey] printKeys.append((key[0], 'KeyDown | ExtendedKey')) printKeys.append((key[0], 'KeyUp | ExtendedKey')) keys.append((keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.append((keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue if upperKey in holdKeys: hold = True insertIndex = len(keys) - 1 else: hold = False else: printKeys.append((key[0], 'UnicodeChar')) keys.append((key[0], 'UnicodeChar')) lastKeyValue = key[0] i = rindex + 1 elif text[i] == '(': if hold: include = True else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] i += 1 elif text[i] == ')': if hold: include = False hold = False else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] i += 1 else: if hold: if text[i] in CharacterCodes: keyValue = CharacterCodes[text[i]] if include and type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue: insertIndex += 1 printKeys.insert(insertIndex, (text[i], 'KeyDown | ExtendedKey')) printKeys.insert(insertIndex + 1, (text[i], 'KeyUp | ExtendedKey')) keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] if include: insertIndex += 1 else: hold = False else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] i += 1 if i >= length: break hotkeyInterval = 0.01 for i, key in enumerate(keys): if key[1] == 'UnicodeChar': SendUnicodeChar(key[0]) time.sleep(interval) if debug: Logger.ColorfullyWrite('<Color=DarkGreen>{}</Color>, sleep({})\n'.format(printKeys[i], interval), writeToFile=False) else: scanCode = _VKtoSC(key[0]) keybd_event(key[0], scanCode, key[1], 0) if debug: Logger.Write(printKeys[i], ConsoleColor.DarkGreen, writeToFile=False) if i + 1 == len(keys): time.sleep(interval) if debug: Logger.Write(', sleep({})\n'.format(interval), writeToFile=False) else: if key[1] & KeyboardEventFlag.KeyUp: if keys[i + 1][1] == 'UnicodeChar' or keys[i + 1][1] & KeyboardEventFlag.KeyUp == 0: time.sleep(interval) if debug: Logger.Write(', sleep({})\n'.format(interval), writeToFile=False) else: time.sleep(hotkeyInterval) #must sleep for a while, otherwise combined keys may not be caught if debug: Logger.Write(', sleep({})\n'.format(hotkeyInterval), writeToFile=False) else: #KeyboardEventFlag.KeyDown time.sleep(hotkeyInterval) if debug: Logger.Write(', sleep({})\n'.format(hotkeyInterval), writeToFile=False) #make sure hold keys are not pressed #win = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_LWIN) #ctrl = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_CONTROL) #alt = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_MENU) #shift = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_SHIFT) #if win & 0x8000: #Logger.WriteLine('ERROR: WIN is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_LWIN, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) #if ctrl & 0x8000: #Logger.WriteLine('ERROR: CTRL is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_CONTROL, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) #if alt & 0x8000: #Logger.WriteLine('ERROR: ALT is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_MENU, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) #if shift & 0x8000: #Logger.WriteLine('ERROR: SHIFT is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_SHIFT, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
[ "Simulate", "typing", "keys", "on", "keyboard", ".", "text", ":", "str", "keys", "to", "type", ".", "interval", ":", "float", "seconds", "between", "keys", ".", "waitTime", ":", "float", ".", "debug", ":", "bool", "if", "True", "print", "the", "keys", ...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2516-L2701
[ "def", "SendKeys", "(", "text", ":", "str", ",", "interval", ":", "float", "=", "0.01", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ",", "debug", ":", "bool", "=", "False", ")", "->", "None", ":", "holdKeys", "=", "(", "'WIN'", ",", "'...
2cc91060982cc8b777152e698d677cc2989bf263
valid
GetPatternIdInterface
Get pattern COM interface by pattern id. patternId: int, a value in class `PatternId`. Return comtypes._cominterface_meta.
uiautomation/uiautomation.py
def GetPatternIdInterface(patternId: int): """ Get pattern COM interface by pattern id. patternId: int, a value in class `PatternId`. Return comtypes._cominterface_meta. """ global _PatternIdInterfaces if not _PatternIdInterfaces: _PatternIdInterfaces = { # PatternId.AnnotationPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationAnnotationPattern, # PatternId.CustomNavigationPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationCustomNavigationPattern, PatternId.DockPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationDockPattern, # PatternId.DragPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationDragPattern, # PatternId.DropTargetPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationDropTargetPattern, PatternId.ExpandCollapsePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationExpandCollapsePattern, PatternId.GridItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationGridItemPattern, PatternId.GridPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationGridPattern, PatternId.InvokePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationInvokePattern, PatternId.ItemContainerPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationItemContainerPattern, PatternId.LegacyIAccessiblePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationLegacyIAccessiblePattern, PatternId.MultipleViewPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationMultipleViewPattern, # PatternId.ObjectModelPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationObjectModelPattern, PatternId.RangeValuePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationRangeValuePattern, PatternId.ScrollItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationScrollItemPattern, PatternId.ScrollPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationScrollPattern, PatternId.SelectionItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSelectionItemPattern, PatternId.SelectionPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSelectionPattern, # PatternId.SpreadsheetItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetItemPattern, # PatternId.SpreadsheetPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetPattern, # PatternId.StylesPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationStylesPattern, PatternId.SynchronizedInputPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSynchronizedInputPattern, PatternId.TableItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTableItemPattern, PatternId.TablePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTablePattern, # PatternId.TextChildPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextChildPattern, # PatternId.TextEditPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextEditPattern, PatternId.TextPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern, # PatternId.TextPattern2: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern2, PatternId.TogglePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTogglePattern, PatternId.TransformPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern, # PatternId.TransformPattern2: _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern2, PatternId.ValuePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationValuePattern, PatternId.VirtualizedItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationVirtualizedItemPattern, PatternId.WindowPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationWindowPattern, } debug = False #the following patterns dosn't exist on Windows 7 or lower try: _PatternIdInterfaces[PatternId.AnnotationPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationAnnotationPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have AnnotationPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.CustomNavigationPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationCustomNavigationPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have CustomNavigationPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.DragPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationDragPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have DragPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.DropTargetPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationDropTargetPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have DropTargetPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.ObjectModelPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationObjectModelPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have ObjectModelPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.SpreadsheetItemPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetItemPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have SpreadsheetItemPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.SpreadsheetPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have SpreadsheetPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.StylesPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationStylesPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have StylesPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TextChildPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextChildPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have TextChildPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TextEditPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextEditPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have TextEditPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TextPattern2] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern2 except: if debug: Logger.WriteLine('UIAutomationCore does not have TextPattern2.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TransformPattern2] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern2 except: if debug: Logger.WriteLine('UIAutomationCore does not have TransformPattern2.', ConsoleColor.Yellow) return _PatternIdInterfaces[patternId]
def GetPatternIdInterface(patternId: int): """ Get pattern COM interface by pattern id. patternId: int, a value in class `PatternId`. Return comtypes._cominterface_meta. """ global _PatternIdInterfaces if not _PatternIdInterfaces: _PatternIdInterfaces = { # PatternId.AnnotationPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationAnnotationPattern, # PatternId.CustomNavigationPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationCustomNavigationPattern, PatternId.DockPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationDockPattern, # PatternId.DragPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationDragPattern, # PatternId.DropTargetPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationDropTargetPattern, PatternId.ExpandCollapsePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationExpandCollapsePattern, PatternId.GridItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationGridItemPattern, PatternId.GridPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationGridPattern, PatternId.InvokePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationInvokePattern, PatternId.ItemContainerPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationItemContainerPattern, PatternId.LegacyIAccessiblePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationLegacyIAccessiblePattern, PatternId.MultipleViewPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationMultipleViewPattern, # PatternId.ObjectModelPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationObjectModelPattern, PatternId.RangeValuePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationRangeValuePattern, PatternId.ScrollItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationScrollItemPattern, PatternId.ScrollPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationScrollPattern, PatternId.SelectionItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSelectionItemPattern, PatternId.SelectionPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSelectionPattern, # PatternId.SpreadsheetItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetItemPattern, # PatternId.SpreadsheetPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetPattern, # PatternId.StylesPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationStylesPattern, PatternId.SynchronizedInputPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSynchronizedInputPattern, PatternId.TableItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTableItemPattern, PatternId.TablePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTablePattern, # PatternId.TextChildPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextChildPattern, # PatternId.TextEditPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextEditPattern, PatternId.TextPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern, # PatternId.TextPattern2: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern2, PatternId.TogglePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTogglePattern, PatternId.TransformPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern, # PatternId.TransformPattern2: _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern2, PatternId.ValuePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationValuePattern, PatternId.VirtualizedItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationVirtualizedItemPattern, PatternId.WindowPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationWindowPattern, } debug = False #the following patterns dosn't exist on Windows 7 or lower try: _PatternIdInterfaces[PatternId.AnnotationPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationAnnotationPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have AnnotationPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.CustomNavigationPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationCustomNavigationPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have CustomNavigationPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.DragPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationDragPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have DragPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.DropTargetPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationDropTargetPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have DropTargetPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.ObjectModelPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationObjectModelPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have ObjectModelPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.SpreadsheetItemPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetItemPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have SpreadsheetItemPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.SpreadsheetPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have SpreadsheetPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.StylesPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationStylesPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have StylesPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TextChildPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextChildPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have TextChildPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TextEditPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextEditPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have TextEditPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TextPattern2] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern2 except: if debug: Logger.WriteLine('UIAutomationCore does not have TextPattern2.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TransformPattern2] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern2 except: if debug: Logger.WriteLine('UIAutomationCore does not have TransformPattern2.', ConsoleColor.Yellow) return _PatternIdInterfaces[patternId]
[ "Get", "pattern", "COM", "interface", "by", "pattern", "id", ".", "patternId", ":", "int", "a", "value", "in", "class", "PatternId", ".", "Return", "comtypes", ".", "_cominterface_meta", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L3187-L3281
[ "def", "GetPatternIdInterface", "(", "patternId", ":", "int", ")", ":", "global", "_PatternIdInterfaces", "if", "not", "_PatternIdInterfaces", ":", "_PatternIdInterfaces", "=", "{", "# PatternId.AnnotationPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationAnnotatio...
2cc91060982cc8b777152e698d677cc2989bf263
valid
CreatePattern
Create a concreate pattern by pattern id and pattern(POINTER(IUnknown)).
uiautomation/uiautomation.py
def CreatePattern(patternId: int, pattern: ctypes.POINTER(comtypes.IUnknown)): """Create a concreate pattern by pattern id and pattern(POINTER(IUnknown)).""" subPattern = pattern.QueryInterface(GetPatternIdInterface(patternId)) if subPattern: return PatternConstructors[patternId](pattern=subPattern)
def CreatePattern(patternId: int, pattern: ctypes.POINTER(comtypes.IUnknown)): """Create a concreate pattern by pattern id and pattern(POINTER(IUnknown)).""" subPattern = pattern.QueryInterface(GetPatternIdInterface(patternId)) if subPattern: return PatternConstructors[patternId](pattern=subPattern)
[ "Create", "a", "concreate", "pattern", "by", "pattern", "id", "and", "pattern", "(", "POINTER", "(", "IUnknown", "))", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L5144-L5148
[ "def", "CreatePattern", "(", "patternId", ":", "int", ",", "pattern", ":", "ctypes", ".", "POINTER", "(", "comtypes", ".", "IUnknown", ")", ")", ":", "subPattern", "=", "pattern", ".", "QueryInterface", "(", "GetPatternIdInterface", "(", "patternId", ")", ")...
2cc91060982cc8b777152e698d677cc2989bf263
valid
WalkTree
Walk a tree not using recursive algorithm. top: a tree node. getChildren: function(treeNode) -> list. getNextSibling: function(treeNode) -> treeNode. getNextSibling: function(treeNode) -> treeNode. yieldCondition: function(treeNode, depth) -> bool. includeTop: bool, if True yield top first. maxDepth: int, enum depth. If getChildren is valid, ignore getFirstChild and getNextSibling, yield 3 items tuple: (treeNode, depth, remain children count in current depth). If getChildren is not valid, using getFirstChild and getNextSibling, yield 2 items tuple: (treeNode, depth). If yieldCondition is not None, only yield tree nodes that yieldCondition(treeNode, depth)->bool returns True. For example: def GetDirChildren(dir_): if os.path.isdir(dir_): return [os.path.join(dir_, it) for it in os.listdir(dir_)] for it, depth, leftCount in WalkTree('D:\\', getChildren= GetDirChildren): print(it, depth, leftCount)
uiautomation/uiautomation.py
def WalkTree(top, getChildren: Callable = None, getFirstChild: Callable = None, getNextSibling: Callable = None, yieldCondition: Callable = None, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF): """ Walk a tree not using recursive algorithm. top: a tree node. getChildren: function(treeNode) -> list. getNextSibling: function(treeNode) -> treeNode. getNextSibling: function(treeNode) -> treeNode. yieldCondition: function(treeNode, depth) -> bool. includeTop: bool, if True yield top first. maxDepth: int, enum depth. If getChildren is valid, ignore getFirstChild and getNextSibling, yield 3 items tuple: (treeNode, depth, remain children count in current depth). If getChildren is not valid, using getFirstChild and getNextSibling, yield 2 items tuple: (treeNode, depth). If yieldCondition is not None, only yield tree nodes that yieldCondition(treeNode, depth)->bool returns True. For example: def GetDirChildren(dir_): if os.path.isdir(dir_): return [os.path.join(dir_, it) for it in os.listdir(dir_)] for it, depth, leftCount in WalkTree('D:\\', getChildren= GetDirChildren): print(it, depth, leftCount) """ if maxDepth <= 0: return depth = 0 if getChildren: if includeTop: if not yieldCondition or yieldCondition(top, 0): yield top, 0, 0 children = getChildren(top) childList = [children] while depth >= 0: #or while childList: lastItems = childList[-1] if lastItems: if not yieldCondition or yieldCondition(lastItems[0], depth + 1): yield lastItems[0], depth + 1, len(lastItems) - 1 if depth + 1 < maxDepth: children = getChildren(lastItems[0]) if children: depth += 1 childList.append(children) del lastItems[0] else: del childList[depth] depth -= 1 elif getFirstChild and getNextSibling: if includeTop: if not yieldCondition or yieldCondition(top, 0): yield top, 0 child = getFirstChild(top) childList = [child] while depth >= 0: #or while childList: lastItem = childList[-1] if lastItem: if not yieldCondition or yieldCondition(lastItem, depth + 1): yield lastItem, depth + 1 child = getNextSibling(lastItem) childList[depth] = child if depth + 1 < maxDepth: child = getFirstChild(lastItem) if child: depth += 1 childList.append(child) else: del childList[depth] depth -= 1
def WalkTree(top, getChildren: Callable = None, getFirstChild: Callable = None, getNextSibling: Callable = None, yieldCondition: Callable = None, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF): """ Walk a tree not using recursive algorithm. top: a tree node. getChildren: function(treeNode) -> list. getNextSibling: function(treeNode) -> treeNode. getNextSibling: function(treeNode) -> treeNode. yieldCondition: function(treeNode, depth) -> bool. includeTop: bool, if True yield top first. maxDepth: int, enum depth. If getChildren is valid, ignore getFirstChild and getNextSibling, yield 3 items tuple: (treeNode, depth, remain children count in current depth). If getChildren is not valid, using getFirstChild and getNextSibling, yield 2 items tuple: (treeNode, depth). If yieldCondition is not None, only yield tree nodes that yieldCondition(treeNode, depth)->bool returns True. For example: def GetDirChildren(dir_): if os.path.isdir(dir_): return [os.path.join(dir_, it) for it in os.listdir(dir_)] for it, depth, leftCount in WalkTree('D:\\', getChildren= GetDirChildren): print(it, depth, leftCount) """ if maxDepth <= 0: return depth = 0 if getChildren: if includeTop: if not yieldCondition or yieldCondition(top, 0): yield top, 0, 0 children = getChildren(top) childList = [children] while depth >= 0: #or while childList: lastItems = childList[-1] if lastItems: if not yieldCondition or yieldCondition(lastItems[0], depth + 1): yield lastItems[0], depth + 1, len(lastItems) - 1 if depth + 1 < maxDepth: children = getChildren(lastItems[0]) if children: depth += 1 childList.append(children) del lastItems[0] else: del childList[depth] depth -= 1 elif getFirstChild and getNextSibling: if includeTop: if not yieldCondition or yieldCondition(top, 0): yield top, 0 child = getFirstChild(top) childList = [child] while depth >= 0: #or while childList: lastItem = childList[-1] if lastItem: if not yieldCondition or yieldCondition(lastItem, depth + 1): yield lastItem, depth + 1 child = getNextSibling(lastItem) childList[depth] = child if depth + 1 < maxDepth: child = getFirstChild(lastItem) if child: depth += 1 childList.append(child) else: del childList[depth] depth -= 1
[ "Walk", "a", "tree", "not", "using", "recursive", "algorithm", ".", "top", ":", "a", "tree", "node", ".", "getChildren", ":", "function", "(", "treeNode", ")", "-", ">", "list", ".", "getNextSibling", ":", "function", "(", "treeNode", ")", "-", ">", "t...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7367-L7434
[ "def", "WalkTree", "(", "top", ",", "getChildren", ":", "Callable", "=", "None", ",", "getFirstChild", ":", "Callable", "=", "None", ",", "getNextSibling", ":", "Callable", "=", "None", ",", "yieldCondition", ":", "Callable", "=", "None", ",", "includeTop", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
ControlFromPoint
Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon. Return `Control` subclass or None.
uiautomation/uiautomation.py
def ControlFromPoint(x: int, y: int) -> Control: """ Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon. Return `Control` subclass or None. """ element = _AutomationClient.instance().IUIAutomation.ElementFromPoint(ctypes.wintypes.POINT(x, y)) return Control.CreateControlFromElement(element)
def ControlFromPoint(x: int, y: int) -> Control: """ Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon. Return `Control` subclass or None. """ element = _AutomationClient.instance().IUIAutomation.ElementFromPoint(ctypes.wintypes.POINT(x, y)) return Control.CreateControlFromElement(element)
[ "Call", "IUIAutomation", "ElementFromPoint", "x", "y", ".", "May", "return", "None", "if", "mouse", "is", "over", "cmd", "s", "title", "bar", "icon", ".", "Return", "Control", "subclass", "or", "None", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7472-L7478
[ "def", "ControlFromPoint", "(", "x", ":", "int", ",", "y", ":", "int", ")", "->", "Control", ":", "element", "=", "_AutomationClient", ".", "instance", "(", ")", ".", "IUIAutomation", ".", "ElementFromPoint", "(", "ctypes", ".", "wintypes", ".", "POINT", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
ControlFromPoint2
Get a native handle from point x,y and call IUIAutomation.ElementFromHandle. Return `Control` subclass.
uiautomation/uiautomation.py
def ControlFromPoint2(x: int, y: int) -> Control: """ Get a native handle from point x,y and call IUIAutomation.ElementFromHandle. Return `Control` subclass. """ return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(WindowFromPoint(x, y)))
def ControlFromPoint2(x: int, y: int) -> Control: """ Get a native handle from point x,y and call IUIAutomation.ElementFromHandle. Return `Control` subclass. """ return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(WindowFromPoint(x, y)))
[ "Get", "a", "native", "handle", "from", "point", "x", "y", "and", "call", "IUIAutomation", ".", "ElementFromHandle", ".", "Return", "Control", "subclass", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7481-L7486
[ "def", "ControlFromPoint2", "(", "x", ":", "int", ",", "y", ":", "int", ")", "->", "Control", ":", "return", "Control", ".", "CreateControlFromElement", "(", "_AutomationClient", ".", "instance", "(", ")", ".", "IUIAutomation", ".", "ElementFromHandle", "(", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
ControlFromHandle
Call IUIAutomation.ElementFromHandle with a native handle. handle: int, a native window handle. Return `Control` subclass.
uiautomation/uiautomation.py
def ControlFromHandle(handle: int) -> Control: """ Call IUIAutomation.ElementFromHandle with a native handle. handle: int, a native window handle. Return `Control` subclass. """ return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(handle))
def ControlFromHandle(handle: int) -> Control: """ Call IUIAutomation.ElementFromHandle with a native handle. handle: int, a native window handle. Return `Control` subclass. """ return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(handle))
[ "Call", "IUIAutomation", ".", "ElementFromHandle", "with", "a", "native", "handle", ".", "handle", ":", "int", "a", "native", "window", "handle", ".", "Return", "Control", "subclass", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7507-L7513
[ "def", "ControlFromHandle", "(", "handle", ":", "int", ")", "->", "Control", ":", "return", "Control", ".", "CreateControlFromElement", "(", "_AutomationClient", ".", "instance", "(", ")", ".", "IUIAutomation", ".", "ElementFromHandle", "(", "handle", ")", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
ControlsAreSame
control1: `Control` or its subclass. control2: `Control` or its subclass. Return bool, True if control1 and control2 represent the same control otherwise False.
uiautomation/uiautomation.py
def ControlsAreSame(control1: Control, control2: Control) -> bool: """ control1: `Control` or its subclass. control2: `Control` or its subclass. Return bool, True if control1 and control2 represent the same control otherwise False. """ return bool(_AutomationClient.instance().IUIAutomation.CompareElements(control1.Element, control2.Element))
def ControlsAreSame(control1: Control, control2: Control) -> bool: """ control1: `Control` or its subclass. control2: `Control` or its subclass. Return bool, True if control1 and control2 represent the same control otherwise False. """ return bool(_AutomationClient.instance().IUIAutomation.CompareElements(control1.Element, control2.Element))
[ "control1", ":", "Control", "or", "its", "subclass", ".", "control2", ":", "Control", "or", "its", "subclass", ".", "Return", "bool", "True", "if", "control1", "and", "control2", "represent", "the", "same", "control", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7516-L7522
[ "def", "ControlsAreSame", "(", "control1", ":", "Control", ",", "control2", ":", "Control", ")", "->", "bool", ":", "return", "bool", "(", "_AutomationClient", ".", "instance", "(", ")", ".", "IUIAutomation", ".", "CompareElements", "(", "control1", ".", "El...
2cc91060982cc8b777152e698d677cc2989bf263
valid
WalkControl
control: `Control` or its subclass. includeTop: bool, if True, yield (control, 0) first. maxDepth: int, enum depth. Yield 2 items tuple(control: Control, depth: int).
uiautomation/uiautomation.py
def WalkControl(control: Control, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF): """ control: `Control` or its subclass. includeTop: bool, if True, yield (control, 0) first. maxDepth: int, enum depth. Yield 2 items tuple(control: Control, depth: int). """ if includeTop: yield control, 0 if maxDepth <= 0: return depth = 0 child = control.GetFirstChildControl() controlList = [child] while depth >= 0: lastControl = controlList[-1] if lastControl: yield lastControl, depth + 1 child = lastControl.GetNextSiblingControl() controlList[depth] = child if depth + 1 < maxDepth: child = lastControl.GetFirstChildControl() if child: depth += 1 controlList.append(child) else: del controlList[depth] depth -= 1
def WalkControl(control: Control, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF): """ control: `Control` or its subclass. includeTop: bool, if True, yield (control, 0) first. maxDepth: int, enum depth. Yield 2 items tuple(control: Control, depth: int). """ if includeTop: yield control, 0 if maxDepth <= 0: return depth = 0 child = control.GetFirstChildControl() controlList = [child] while depth >= 0: lastControl = controlList[-1] if lastControl: yield lastControl, depth + 1 child = lastControl.GetNextSiblingControl() controlList[depth] = child if depth + 1 < maxDepth: child = lastControl.GetFirstChildControl() if child: depth += 1 controlList.append(child) else: del controlList[depth] depth -= 1
[ "control", ":", "Control", "or", "its", "subclass", ".", "includeTop", ":", "bool", "if", "True", "yield", "(", "control", "0", ")", "first", ".", "maxDepth", ":", "int", "enum", "depth", ".", "Yield", "2", "items", "tuple", "(", "control", ":", "Contr...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7525-L7552
[ "def", "WalkControl", "(", "control", ":", "Control", ",", "includeTop", ":", "bool", "=", "False", ",", "maxDepth", ":", "int", "=", "0xFFFFFFFF", ")", ":", "if", "includeTop", ":", "yield", "control", ",", "0", "if", "maxDepth", "<=", "0", ":", "retu...
2cc91060982cc8b777152e698d677cc2989bf263
valid
LogControl
Print and log control's properties. control: `Control` or its subclass. depth: int, current depth. showAllName: bool, if False, print the first 30 characters of control.Name.
uiautomation/uiautomation.py
def LogControl(control: Control, depth: int = 0, showAllName: bool = True) -> None: """ Print and log control's properties. control: `Control` or its subclass. depth: int, current depth. showAllName: bool, if False, print the first 30 characters of control.Name. """ def getKeyName(theDict, theValue): for key in theDict: if theValue == theDict[key]: return key indent = ' ' * depth * 4 Logger.Write('{0}ControlType: '.format(indent)) Logger.Write(control.ControlTypeName, ConsoleColor.DarkGreen) Logger.Write(' ClassName: ') Logger.Write(control.ClassName, ConsoleColor.DarkGreen) Logger.Write(' AutomationId: ') Logger.Write(control.AutomationId, ConsoleColor.DarkGreen) Logger.Write(' Rect: ') Logger.Write(control.BoundingRectangle, ConsoleColor.DarkGreen) Logger.Write(' Name: ') Logger.Write(control.Name, ConsoleColor.DarkGreen, printTruncateLen=0 if showAllName else 30) Logger.Write(' Handle: ') Logger.Write('0x{0:X}({0})'.format(control.NativeWindowHandle), ConsoleColor.DarkGreen) Logger.Write(' Depth: ') Logger.Write(depth, ConsoleColor.DarkGreen) supportedPatterns = list(filter(lambda t: t[0], ((control.GetPattern(id_), name) for id_, name in PatternIdNames.items()))) for pt, name in supportedPatterns: if isinstance(pt, ValuePattern): Logger.Write(' ValuePattern.Value: ') Logger.Write(pt.Value, ConsoleColor.DarkGreen, printTruncateLen=0 if showAllName else 30) elif isinstance(pt, RangeValuePattern): Logger.Write(' RangeValuePattern.Value: ') Logger.Write(pt.Value, ConsoleColor.DarkGreen) elif isinstance(pt, TogglePattern): Logger.Write(' TogglePattern.ToggleState: ') Logger.Write('ToggleState.' + getKeyName(ToggleState.__dict__, pt.ToggleState), ConsoleColor.DarkGreen) elif isinstance(pt, SelectionItemPattern): Logger.Write(' SelectionItemPattern.IsSelected: ') Logger.Write(pt.IsSelected, ConsoleColor.DarkGreen) elif isinstance(pt, ExpandCollapsePattern): Logger.Write(' ExpandCollapsePattern.ExpandCollapseState: ') Logger.Write('ExpandCollapseState.' + getKeyName(ExpandCollapseState.__dict__, pt.ExpandCollapseState), ConsoleColor.DarkGreen) elif isinstance(pt, ScrollPattern): Logger.Write(' ScrollPattern.HorizontalScrollPercent: ') Logger.Write(pt.HorizontalScrollPercent, ConsoleColor.DarkGreen) Logger.Write(' ScrollPattern.VerticalScrollPercent: ') Logger.Write(pt.VerticalScrollPercent, ConsoleColor.DarkGreen) elif isinstance(pt, GridPattern): Logger.Write(' GridPattern.RowCount: ') Logger.Write(pt.RowCount, ConsoleColor.DarkGreen) Logger.Write(' GridPattern.ColumnCount: ') Logger.Write(pt.ColumnCount, ConsoleColor.DarkGreen) elif isinstance(pt, GridItemPattern): Logger.Write(' GridItemPattern.Row: ') Logger.Write(pt.Column, ConsoleColor.DarkGreen) Logger.Write(' GridItemPattern.Column: ') Logger.Write(pt.Column, ConsoleColor.DarkGreen) elif isinstance(pt, TextPattern): Logger.Write(' TextPattern.Text: ') Logger.Write(pt.DocumentRange.GetText(30), ConsoleColor.DarkGreen) Logger.Write(' SupportedPattern:') for pt, name in supportedPatterns: Logger.Write(' ' + name, ConsoleColor.DarkGreen) Logger.Write('\n')
def LogControl(control: Control, depth: int = 0, showAllName: bool = True) -> None: """ Print and log control's properties. control: `Control` or its subclass. depth: int, current depth. showAllName: bool, if False, print the first 30 characters of control.Name. """ def getKeyName(theDict, theValue): for key in theDict: if theValue == theDict[key]: return key indent = ' ' * depth * 4 Logger.Write('{0}ControlType: '.format(indent)) Logger.Write(control.ControlTypeName, ConsoleColor.DarkGreen) Logger.Write(' ClassName: ') Logger.Write(control.ClassName, ConsoleColor.DarkGreen) Logger.Write(' AutomationId: ') Logger.Write(control.AutomationId, ConsoleColor.DarkGreen) Logger.Write(' Rect: ') Logger.Write(control.BoundingRectangle, ConsoleColor.DarkGreen) Logger.Write(' Name: ') Logger.Write(control.Name, ConsoleColor.DarkGreen, printTruncateLen=0 if showAllName else 30) Logger.Write(' Handle: ') Logger.Write('0x{0:X}({0})'.format(control.NativeWindowHandle), ConsoleColor.DarkGreen) Logger.Write(' Depth: ') Logger.Write(depth, ConsoleColor.DarkGreen) supportedPatterns = list(filter(lambda t: t[0], ((control.GetPattern(id_), name) for id_, name in PatternIdNames.items()))) for pt, name in supportedPatterns: if isinstance(pt, ValuePattern): Logger.Write(' ValuePattern.Value: ') Logger.Write(pt.Value, ConsoleColor.DarkGreen, printTruncateLen=0 if showAllName else 30) elif isinstance(pt, RangeValuePattern): Logger.Write(' RangeValuePattern.Value: ') Logger.Write(pt.Value, ConsoleColor.DarkGreen) elif isinstance(pt, TogglePattern): Logger.Write(' TogglePattern.ToggleState: ') Logger.Write('ToggleState.' + getKeyName(ToggleState.__dict__, pt.ToggleState), ConsoleColor.DarkGreen) elif isinstance(pt, SelectionItemPattern): Logger.Write(' SelectionItemPattern.IsSelected: ') Logger.Write(pt.IsSelected, ConsoleColor.DarkGreen) elif isinstance(pt, ExpandCollapsePattern): Logger.Write(' ExpandCollapsePattern.ExpandCollapseState: ') Logger.Write('ExpandCollapseState.' + getKeyName(ExpandCollapseState.__dict__, pt.ExpandCollapseState), ConsoleColor.DarkGreen) elif isinstance(pt, ScrollPattern): Logger.Write(' ScrollPattern.HorizontalScrollPercent: ') Logger.Write(pt.HorizontalScrollPercent, ConsoleColor.DarkGreen) Logger.Write(' ScrollPattern.VerticalScrollPercent: ') Logger.Write(pt.VerticalScrollPercent, ConsoleColor.DarkGreen) elif isinstance(pt, GridPattern): Logger.Write(' GridPattern.RowCount: ') Logger.Write(pt.RowCount, ConsoleColor.DarkGreen) Logger.Write(' GridPattern.ColumnCount: ') Logger.Write(pt.ColumnCount, ConsoleColor.DarkGreen) elif isinstance(pt, GridItemPattern): Logger.Write(' GridItemPattern.Row: ') Logger.Write(pt.Column, ConsoleColor.DarkGreen) Logger.Write(' GridItemPattern.Column: ') Logger.Write(pt.Column, ConsoleColor.DarkGreen) elif isinstance(pt, TextPattern): Logger.Write(' TextPattern.Text: ') Logger.Write(pt.DocumentRange.GetText(30), ConsoleColor.DarkGreen) Logger.Write(' SupportedPattern:') for pt, name in supportedPatterns: Logger.Write(' ' + name, ConsoleColor.DarkGreen) Logger.Write('\n')
[ "Print", "and", "log", "control", "s", "properties", ".", "control", ":", "Control", "or", "its", "subclass", ".", "depth", ":", "int", "current", "depth", ".", "showAllName", ":", "bool", "if", "False", "print", "the", "first", "30", "characters", "of", ...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7555-L7619
[ "def", "LogControl", "(", "control", ":", "Control", ",", "depth", ":", "int", "=", "0", ",", "showAllName", ":", "bool", "=", "True", ")", "->", "None", ":", "def", "getKeyName", "(", "theDict", ",", "theValue", ")", ":", "for", "key", "in", "theDic...
2cc91060982cc8b777152e698d677cc2989bf263
valid
EnumAndLogControl
Print and log control and its descendants' propertyies. control: `Control` or its subclass. maxDepth: int, enum depth. showAllName: bool, if False, print the first 30 characters of control.Name. startDepth: int, control's current depth.
uiautomation/uiautomation.py
def EnumAndLogControl(control: Control, maxDepth: int = 0xFFFFFFFF, showAllName: bool = True, startDepth: int = 0) -> None: """ Print and log control and its descendants' propertyies. control: `Control` or its subclass. maxDepth: int, enum depth. showAllName: bool, if False, print the first 30 characters of control.Name. startDepth: int, control's current depth. """ for c, d in WalkControl(control, True, maxDepth): LogControl(c, d + startDepth, showAllName)
def EnumAndLogControl(control: Control, maxDepth: int = 0xFFFFFFFF, showAllName: bool = True, startDepth: int = 0) -> None: """ Print and log control and its descendants' propertyies. control: `Control` or its subclass. maxDepth: int, enum depth. showAllName: bool, if False, print the first 30 characters of control.Name. startDepth: int, control's current depth. """ for c, d in WalkControl(control, True, maxDepth): LogControl(c, d + startDepth, showAllName)
[ "Print", "and", "log", "control", "and", "its", "descendants", "propertyies", ".", "control", ":", "Control", "or", "its", "subclass", ".", "maxDepth", ":", "int", "enum", "depth", ".", "showAllName", ":", "bool", "if", "False", "print", "the", "first", "3...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7622-L7631
[ "def", "EnumAndLogControl", "(", "control", ":", "Control", ",", "maxDepth", ":", "int", "=", "0xFFFFFFFF", ",", "showAllName", ":", "bool", "=", "True", ",", "startDepth", ":", "int", "=", "0", ")", "->", "None", ":", "for", "c", ",", "d", "in", "Wa...
2cc91060982cc8b777152e698d677cc2989bf263
valid
EnumAndLogControlAncestors
Print and log control and its ancestors' propertyies. control: `Control` or its subclass. showAllName: bool, if False, print the first 30 characters of control.Name.
uiautomation/uiautomation.py
def EnumAndLogControlAncestors(control: Control, showAllName: bool = True) -> None: """ Print and log control and its ancestors' propertyies. control: `Control` or its subclass. showAllName: bool, if False, print the first 30 characters of control.Name. """ lists = [] while control: lists.insert(0, control) control = control.GetParentControl() for i, control in enumerate(lists): LogControl(control, i, showAllName)
def EnumAndLogControlAncestors(control: Control, showAllName: bool = True) -> None: """ Print and log control and its ancestors' propertyies. control: `Control` or its subclass. showAllName: bool, if False, print the first 30 characters of control.Name. """ lists = [] while control: lists.insert(0, control) control = control.GetParentControl() for i, control in enumerate(lists): LogControl(control, i, showAllName)
[ "Print", "and", "log", "control", "and", "its", "ancestors", "propertyies", ".", "control", ":", "Control", "or", "its", "subclass", ".", "showAllName", ":", "bool", "if", "False", "print", "the", "first", "30", "characters", "of", "control", ".", "Name", ...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7634-L7645
[ "def", "EnumAndLogControlAncestors", "(", "control", ":", "Control", ",", "showAllName", ":", "bool", "=", "True", ")", "->", "None", ":", "lists", "=", "[", "]", "while", "control", ":", "lists", ".", "insert", "(", "0", ",", "control", ")", "control", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
FindControl
control: `Control` or its subclass. compare: compare function with parameters (control: Control, depth: int) which returns bool. maxDepth: int, enum depth. findFromSelf: bool, if False, do not compare self. foundIndex: int, starts with 1, >= 1. Return `Control` subclass or None if not find.
uiautomation/uiautomation.py
def FindControl(control: Control, compare: Callable, maxDepth: int = 0xFFFFFFFF, findFromSelf: bool = False, foundIndex: int = 1) -> Control: """ control: `Control` or its subclass. compare: compare function with parameters (control: Control, depth: int) which returns bool. maxDepth: int, enum depth. findFromSelf: bool, if False, do not compare self. foundIndex: int, starts with 1, >= 1. Return `Control` subclass or None if not find. """ foundCount = 0 if not control: control = GetRootControl() traverseCount = 0 for child, depth in WalkControl(control, findFromSelf, maxDepth): traverseCount += 1 if compare(child, depth): foundCount += 1 if foundCount == foundIndex: child.traverseCount = traverseCount return child
def FindControl(control: Control, compare: Callable, maxDepth: int = 0xFFFFFFFF, findFromSelf: bool = False, foundIndex: int = 1) -> Control: """ control: `Control` or its subclass. compare: compare function with parameters (control: Control, depth: int) which returns bool. maxDepth: int, enum depth. findFromSelf: bool, if False, do not compare self. foundIndex: int, starts with 1, >= 1. Return `Control` subclass or None if not find. """ foundCount = 0 if not control: control = GetRootControl() traverseCount = 0 for child, depth in WalkControl(control, findFromSelf, maxDepth): traverseCount += 1 if compare(child, depth): foundCount += 1 if foundCount == foundIndex: child.traverseCount = traverseCount return child
[ "control", ":", "Control", "or", "its", "subclass", ".", "compare", ":", "compare", "function", "with", "parameters", "(", "control", ":", "Control", "depth", ":", "int", ")", "which", "returns", "bool", ".", "maxDepth", ":", "int", "enum", "depth", ".", ...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7648-L7667
[ "def", "FindControl", "(", "control", ":", "Control", ",", "compare", ":", "Callable", ",", "maxDepth", ":", "int", "=", "0xFFFFFFFF", ",", "findFromSelf", ":", "bool", "=", "False", ",", "foundIndex", ":", "int", "=", "1", ")", "->", "Control", ":", "...
2cc91060982cc8b777152e698d677cc2989bf263
valid
WaitHotKeyReleased
hotkey: tuple, two ints tuple(modifierKey, key)
uiautomation/uiautomation.py
def WaitHotKeyReleased(hotkey: tuple) -> None: """hotkey: tuple, two ints tuple(modifierKey, key)""" mod = {ModifierKey.Alt: Keys.VK_MENU, ModifierKey.Control: Keys.VK_CONTROL, ModifierKey.Shift: Keys.VK_SHIFT, ModifierKey.Win: Keys.VK_LWIN } while True: time.sleep(0.05) if IsKeyPressed(hotkey[1]): continue for k, v in mod.items(): if k & hotkey[0]: if IsKeyPressed(v): break else: break
def WaitHotKeyReleased(hotkey: tuple) -> None: """hotkey: tuple, two ints tuple(modifierKey, key)""" mod = {ModifierKey.Alt: Keys.VK_MENU, ModifierKey.Control: Keys.VK_CONTROL, ModifierKey.Shift: Keys.VK_SHIFT, ModifierKey.Win: Keys.VK_LWIN } while True: time.sleep(0.05) if IsKeyPressed(hotkey[1]): continue for k, v in mod.items(): if k & hotkey[0]: if IsKeyPressed(v): break else: break
[ "hotkey", ":", "tuple", "two", "ints", "tuple", "(", "modifierKey", "key", ")" ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7703-L7719
[ "def", "WaitHotKeyReleased", "(", "hotkey", ":", "tuple", ")", "->", "None", ":", "mod", "=", "{", "ModifierKey", ".", "Alt", ":", "Keys", ".", "VK_MENU", ",", "ModifierKey", ".", "Control", ":", "Keys", ".", "VK_CONTROL", ",", "ModifierKey", ".", "Shift...
2cc91060982cc8b777152e698d677cc2989bf263
valid
RunByHotKey
Bind functions with hotkeys, the function will be run or stopped in another thread when the hotkey is pressed. keyFunctions: hotkey function dict, like {(uiautomation.ModifierKey.Control, uiautomation.Keys.VK_1) : func} stopHotKey: hotkey tuple exitHotKey: hotkey tuple waitHotKeyReleased: bool, if True, hotkey function will be triggered after the hotkey is released def main(stopEvent): while True: if stopEvent.is_set(): # must check stopEvent.is_set() if you want to stop when stop hotkey is pressed break print(n) n += 1 stopEvent.wait(1) print('main exit') uiautomation.RunByHotKey({(uiautomation.ModifierKey.Control, uiautomation.Keys.VK_1) : main} , (uiautomation.ModifierKey.Control | uiautomation.ModifierKey.Shift, uiautomation.Keys.VK_2))
uiautomation/uiautomation.py
def RunByHotKey(keyFunctions: dict, stopHotKey: tuple = None, exitHotKey: tuple = (ModifierKey.Control, Keys.VK_D), waitHotKeyReleased: bool = True) -> None: """ Bind functions with hotkeys, the function will be run or stopped in another thread when the hotkey is pressed. keyFunctions: hotkey function dict, like {(uiautomation.ModifierKey.Control, uiautomation.Keys.VK_1) : func} stopHotKey: hotkey tuple exitHotKey: hotkey tuple waitHotKeyReleased: bool, if True, hotkey function will be triggered after the hotkey is released def main(stopEvent): while True: if stopEvent.is_set(): # must check stopEvent.is_set() if you want to stop when stop hotkey is pressed break print(n) n += 1 stopEvent.wait(1) print('main exit') uiautomation.RunByHotKey({(uiautomation.ModifierKey.Control, uiautomation.Keys.VK_1) : main} , (uiautomation.ModifierKey.Control | uiautomation.ModifierKey.Shift, uiautomation.Keys.VK_2)) """ from threading import Thread, Event, currentThread import traceback def getModName(theDict, theValue): name = '' for key in theDict: if isinstance(theDict[key], int) and theValue & theDict[key]: if name: name += '|' name += key return name def getKeyName(theDict, theValue): for key in theDict: if theValue == theDict[key]: return key def releaseAllKey(): for key, value in Keys.__dict__.items(): if isinstance(value, int) and key.startswith('VK'): if IsKeyPressed(value): ReleaseKey(value) def threadFunc(function, stopEvent, hotkey, hotkeyName): if waitHotKeyReleased: WaitHotKeyReleased(hotkey) try: function(stopEvent) except Exception as ex: Logger.ColorfullyWrite('Catch an exception <Color=Red>{}</Color> in thread for hotkey <Color=DarkCyan>{}</Color>\n'.format( ex.__class__.__name__, hotkeyName), writeToFile=False) print(traceback.format_exc()) finally: releaseAllKey() #need to release keys if some keys were pressed Logger.ColorfullyWrite('{} for function <Color=DarkCyan>{}</Color> exits, hotkey <Color=DarkCyan>{}</Color>\n'.format( currentThread(), function.__name__, hotkeyName), ConsoleColor.DarkYellow, writeToFile=False) stopHotKeyId = 1 exitHotKeyId = 2 hotKeyId = 3 registed = True id2HotKey = {} id2Function = {} id2Thread = {} id2Name = {} for hotkey in keyFunctions: id2HotKey[hotKeyId] = hotkey id2Function[hotKeyId] = keyFunctions[hotkey] id2Thread[hotKeyId] = None modName = getModName(ModifierKey.__dict__, hotkey[0]) keyName = getKeyName(Keys.__dict__, hotkey[1]) id2Name[hotKeyId] = str((modName, keyName)) if ctypes.windll.user32.RegisterHotKey(0, hotKeyId, hotkey[0], hotkey[1]): Logger.ColorfullyWrite('Register hotkey <Color=DarkGreen>{}</Color> successfully\n'.format((modName, keyName)), writeToFile=False) else: registed = False Logger.ColorfullyWrite('Register hotkey <Color=DarkGreen>{}</Color> unsuccessfully, maybe it was allready registered by another program\n'.format((modName, keyName)), writeToFile=False) hotKeyId += 1 if stopHotKey and len(stopHotKey) == 2: modName = getModName(ModifierKey.__dict__, stopHotKey[0]) keyName = getKeyName(Keys.__dict__, stopHotKey[1]) if ctypes.windll.user32.RegisterHotKey(0, stopHotKeyId, stopHotKey[0], stopHotKey[1]): Logger.ColorfullyWrite('Register stop hotkey <Color=DarkYellow>{}</Color> successfully\n'.format((modName, keyName)), writeToFile=False) else: registed = False Logger.ColorfullyWrite('Register stop hotkey <Color=DarkYellow>{}</Color> unsuccessfully, maybe it was allready registered by another program\n'.format((modName, keyName)), writeToFile=False) if not registed: return if exitHotKey and len(exitHotKey) == 2: modName = getModName(ModifierKey.__dict__, exitHotKey[0]) keyName = getKeyName(Keys.__dict__, exitHotKey[1]) if ctypes.windll.user32.RegisterHotKey(0, exitHotKeyId, exitHotKey[0], exitHotKey[1]): Logger.ColorfullyWrite('Register exit hotkey <Color=DarkYellow>{}</Color> successfully\n'.format((modName, keyName)), writeToFile=False) else: Logger.ColorfullyWrite('Register exit hotkey <Color=DarkYellow>{}</Color> unsuccessfully\n'.format((modName, keyName)), writeToFile=False) funcThread = None livingThreads = [] stopEvent = Event() msg = ctypes.wintypes.MSG() while ctypes.windll.user32.GetMessageW(ctypes.byref(msg), ctypes.c_void_p(0), 0, 0) != 0: if msg.message == 0x0312: # WM_HOTKEY=0x0312 if msg.wParam in id2HotKey: if msg.lParam & 0x0000FFFF == id2HotKey[msg.wParam][0] and msg.lParam >> 16 & 0x0000FFFF == id2HotKey[msg.wParam][1]: Logger.ColorfullyWrite('----------hotkey <Color=DarkGreen>{}</Color> pressed----------\n'.format(id2Name[msg.wParam]), writeToFile=False) if not id2Thread[msg.wParam]: stopEvent.clear() funcThread = Thread(None, threadFunc, args=(id2Function[msg.wParam], stopEvent, id2HotKey[msg.wParam], id2Name[msg.wParam])) funcThread.start() id2Thread[msg.wParam] = funcThread else: if id2Thread[msg.wParam].is_alive(): Logger.WriteLine('There is a {} that is already running for hotkey {}'.format(id2Thread[msg.wParam], id2Name[msg.wParam]), ConsoleColor.Yellow, writeToFile=False) else: stopEvent.clear() funcThread = Thread(None, threadFunc, args=(id2Function[msg.wParam], stopEvent, id2HotKey[msg.wParam], id2Name[msg.wParam])) funcThread.start() id2Thread[msg.wParam] = funcThread elif stopHotKeyId == msg.wParam: if msg.lParam & 0x0000FFFF == stopHotKey[0] and msg.lParam >> 16 & 0x0000FFFF == stopHotKey[1]: Logger.Write('----------stop hotkey pressed----------\n', ConsoleColor.DarkYellow, writeToFile=False) stopEvent.set() for id_ in id2Thread: if id2Thread[id_]: if id2Thread[id_].is_alive(): livingThreads.append((id2Thread[id_], id2Name[id_])) id2Thread[id_] = None elif exitHotKeyId == msg.wParam: if msg.lParam & 0x0000FFFF == exitHotKey[0] and msg.lParam >> 16 & 0x0000FFFF == exitHotKey[1]: Logger.Write('Exit hotkey pressed. Exit\n', ConsoleColor.DarkYellow, writeToFile=False) stopEvent.set() for id_ in id2Thread: if id2Thread[id_]: if id2Thread[id_].is_alive(): livingThreads.append((id2Thread[id_], id2Name[id_])) id2Thread[id_] = None break for thread, hotkeyName in livingThreads: if thread.is_alive(): Logger.Write('join {} triggered by hotkey {}\n'.format(thread, hotkeyName), ConsoleColor.DarkYellow, writeToFile=False) thread.join(2) os._exit(0)
def RunByHotKey(keyFunctions: dict, stopHotKey: tuple = None, exitHotKey: tuple = (ModifierKey.Control, Keys.VK_D), waitHotKeyReleased: bool = True) -> None: """ Bind functions with hotkeys, the function will be run or stopped in another thread when the hotkey is pressed. keyFunctions: hotkey function dict, like {(uiautomation.ModifierKey.Control, uiautomation.Keys.VK_1) : func} stopHotKey: hotkey tuple exitHotKey: hotkey tuple waitHotKeyReleased: bool, if True, hotkey function will be triggered after the hotkey is released def main(stopEvent): while True: if stopEvent.is_set(): # must check stopEvent.is_set() if you want to stop when stop hotkey is pressed break print(n) n += 1 stopEvent.wait(1) print('main exit') uiautomation.RunByHotKey({(uiautomation.ModifierKey.Control, uiautomation.Keys.VK_1) : main} , (uiautomation.ModifierKey.Control | uiautomation.ModifierKey.Shift, uiautomation.Keys.VK_2)) """ from threading import Thread, Event, currentThread import traceback def getModName(theDict, theValue): name = '' for key in theDict: if isinstance(theDict[key], int) and theValue & theDict[key]: if name: name += '|' name += key return name def getKeyName(theDict, theValue): for key in theDict: if theValue == theDict[key]: return key def releaseAllKey(): for key, value in Keys.__dict__.items(): if isinstance(value, int) and key.startswith('VK'): if IsKeyPressed(value): ReleaseKey(value) def threadFunc(function, stopEvent, hotkey, hotkeyName): if waitHotKeyReleased: WaitHotKeyReleased(hotkey) try: function(stopEvent) except Exception as ex: Logger.ColorfullyWrite('Catch an exception <Color=Red>{}</Color> in thread for hotkey <Color=DarkCyan>{}</Color>\n'.format( ex.__class__.__name__, hotkeyName), writeToFile=False) print(traceback.format_exc()) finally: releaseAllKey() #need to release keys if some keys were pressed Logger.ColorfullyWrite('{} for function <Color=DarkCyan>{}</Color> exits, hotkey <Color=DarkCyan>{}</Color>\n'.format( currentThread(), function.__name__, hotkeyName), ConsoleColor.DarkYellow, writeToFile=False) stopHotKeyId = 1 exitHotKeyId = 2 hotKeyId = 3 registed = True id2HotKey = {} id2Function = {} id2Thread = {} id2Name = {} for hotkey in keyFunctions: id2HotKey[hotKeyId] = hotkey id2Function[hotKeyId] = keyFunctions[hotkey] id2Thread[hotKeyId] = None modName = getModName(ModifierKey.__dict__, hotkey[0]) keyName = getKeyName(Keys.__dict__, hotkey[1]) id2Name[hotKeyId] = str((modName, keyName)) if ctypes.windll.user32.RegisterHotKey(0, hotKeyId, hotkey[0], hotkey[1]): Logger.ColorfullyWrite('Register hotkey <Color=DarkGreen>{}</Color> successfully\n'.format((modName, keyName)), writeToFile=False) else: registed = False Logger.ColorfullyWrite('Register hotkey <Color=DarkGreen>{}</Color> unsuccessfully, maybe it was allready registered by another program\n'.format((modName, keyName)), writeToFile=False) hotKeyId += 1 if stopHotKey and len(stopHotKey) == 2: modName = getModName(ModifierKey.__dict__, stopHotKey[0]) keyName = getKeyName(Keys.__dict__, stopHotKey[1]) if ctypes.windll.user32.RegisterHotKey(0, stopHotKeyId, stopHotKey[0], stopHotKey[1]): Logger.ColorfullyWrite('Register stop hotkey <Color=DarkYellow>{}</Color> successfully\n'.format((modName, keyName)), writeToFile=False) else: registed = False Logger.ColorfullyWrite('Register stop hotkey <Color=DarkYellow>{}</Color> unsuccessfully, maybe it was allready registered by another program\n'.format((modName, keyName)), writeToFile=False) if not registed: return if exitHotKey and len(exitHotKey) == 2: modName = getModName(ModifierKey.__dict__, exitHotKey[0]) keyName = getKeyName(Keys.__dict__, exitHotKey[1]) if ctypes.windll.user32.RegisterHotKey(0, exitHotKeyId, exitHotKey[0], exitHotKey[1]): Logger.ColorfullyWrite('Register exit hotkey <Color=DarkYellow>{}</Color> successfully\n'.format((modName, keyName)), writeToFile=False) else: Logger.ColorfullyWrite('Register exit hotkey <Color=DarkYellow>{}</Color> unsuccessfully\n'.format((modName, keyName)), writeToFile=False) funcThread = None livingThreads = [] stopEvent = Event() msg = ctypes.wintypes.MSG() while ctypes.windll.user32.GetMessageW(ctypes.byref(msg), ctypes.c_void_p(0), 0, 0) != 0: if msg.message == 0x0312: # WM_HOTKEY=0x0312 if msg.wParam in id2HotKey: if msg.lParam & 0x0000FFFF == id2HotKey[msg.wParam][0] and msg.lParam >> 16 & 0x0000FFFF == id2HotKey[msg.wParam][1]: Logger.ColorfullyWrite('----------hotkey <Color=DarkGreen>{}</Color> pressed----------\n'.format(id2Name[msg.wParam]), writeToFile=False) if not id2Thread[msg.wParam]: stopEvent.clear() funcThread = Thread(None, threadFunc, args=(id2Function[msg.wParam], stopEvent, id2HotKey[msg.wParam], id2Name[msg.wParam])) funcThread.start() id2Thread[msg.wParam] = funcThread else: if id2Thread[msg.wParam].is_alive(): Logger.WriteLine('There is a {} that is already running for hotkey {}'.format(id2Thread[msg.wParam], id2Name[msg.wParam]), ConsoleColor.Yellow, writeToFile=False) else: stopEvent.clear() funcThread = Thread(None, threadFunc, args=(id2Function[msg.wParam], stopEvent, id2HotKey[msg.wParam], id2Name[msg.wParam])) funcThread.start() id2Thread[msg.wParam] = funcThread elif stopHotKeyId == msg.wParam: if msg.lParam & 0x0000FFFF == stopHotKey[0] and msg.lParam >> 16 & 0x0000FFFF == stopHotKey[1]: Logger.Write('----------stop hotkey pressed----------\n', ConsoleColor.DarkYellow, writeToFile=False) stopEvent.set() for id_ in id2Thread: if id2Thread[id_]: if id2Thread[id_].is_alive(): livingThreads.append((id2Thread[id_], id2Name[id_])) id2Thread[id_] = None elif exitHotKeyId == msg.wParam: if msg.lParam & 0x0000FFFF == exitHotKey[0] and msg.lParam >> 16 & 0x0000FFFF == exitHotKey[1]: Logger.Write('Exit hotkey pressed. Exit\n', ConsoleColor.DarkYellow, writeToFile=False) stopEvent.set() for id_ in id2Thread: if id2Thread[id_]: if id2Thread[id_].is_alive(): livingThreads.append((id2Thread[id_], id2Name[id_])) id2Thread[id_] = None break for thread, hotkeyName in livingThreads: if thread.is_alive(): Logger.Write('join {} triggered by hotkey {}\n'.format(thread, hotkeyName), ConsoleColor.DarkYellow, writeToFile=False) thread.join(2) os._exit(0)
[ "Bind", "functions", "with", "hotkeys", "the", "function", "will", "be", "run", "or", "stopped", "in", "another", "thread", "when", "the", "hotkey", "is", "pressed", ".", "keyFunctions", ":", "hotkey", "function", "dict", "like", "{", "(", "uiautomation", "....
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L7722-L7859
[ "def", "RunByHotKey", "(", "keyFunctions", ":", "dict", ",", "stopHotKey", ":", "tuple", "=", "None", ",", "exitHotKey", ":", "tuple", "=", "(", "ModifierKey", ".", "Control", ",", "Keys", ".", "VK_D", ")", ",", "waitHotKeyReleased", ":", "bool", "=", "T...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Logger.Write
log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. printTruncateLen: int, if <= 0, log is not truncated when print.
uiautomation/uiautomation.py
def Write(log: Any, consoleColor: int = ConsoleColor.Default, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None, printTruncateLen: int = 0) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. printTruncateLen: int, if <= 0, log is not truncated when print. """ if not isinstance(log, str): log = str(log) if printToStdout and sys.stdout: isValidColor = (consoleColor >= ConsoleColor.Black and consoleColor <= ConsoleColor.White) if isValidColor: SetConsoleColor(consoleColor) try: if printTruncateLen > 0 and len(log) > printTruncateLen: sys.stdout.write(log[:printTruncateLen] + '...') else: sys.stdout.write(log) except Exception as ex: SetConsoleColor(ConsoleColor.Red) isValidColor = True sys.stdout.write(ex.__class__.__name__ + ': can\'t print the log!') if log.endswith('\n'): sys.stdout.write('\n') if isValidColor: ResetConsoleColor() sys.stdout.flush() if not writeToFile: return fileName = logFile if logFile else Logger.FileName try: fout = open(fileName, 'a+', encoding='utf-8') fout.write(log) except Exception as ex: if sys.stdout: sys.stdout.write(ex.__class__.__name__ + ': can\'t write the log!') finally: if fout: fout.close()
def Write(log: Any, consoleColor: int = ConsoleColor.Default, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None, printTruncateLen: int = 0) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. printTruncateLen: int, if <= 0, log is not truncated when print. """ if not isinstance(log, str): log = str(log) if printToStdout and sys.stdout: isValidColor = (consoleColor >= ConsoleColor.Black and consoleColor <= ConsoleColor.White) if isValidColor: SetConsoleColor(consoleColor) try: if printTruncateLen > 0 and len(log) > printTruncateLen: sys.stdout.write(log[:printTruncateLen] + '...') else: sys.stdout.write(log) except Exception as ex: SetConsoleColor(ConsoleColor.Red) isValidColor = True sys.stdout.write(ex.__class__.__name__ + ': can\'t print the log!') if log.endswith('\n'): sys.stdout.write('\n') if isValidColor: ResetConsoleColor() sys.stdout.flush() if not writeToFile: return fileName = logFile if logFile else Logger.FileName try: fout = open(fileName, 'a+', encoding='utf-8') fout.write(log) except Exception as ex: if sys.stdout: sys.stdout.write(ex.__class__.__name__ + ': can\'t write the log!') finally: if fout: fout.close()
[ "log", ":", "any", "type", ".", "consoleColor", ":", "int", "a", "value", "in", "class", "ConsoleColor", "such", "as", "ConsoleColor", ".", "DarkGreen", ".", "writeToFile", ":", "bool", ".", "printToStdout", ":", "bool", ".", "logFile", ":", "str", "log", ...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2762-L2802
[ "def", "Write", "(", "log", ":", "Any", ",", "consoleColor", ":", "int", "=", "ConsoleColor", ".", "Default", ",", "writeToFile", ":", "bool", "=", "True", ",", "printToStdout", ":", "bool", "=", "True", ",", "logFile", ":", "str", "=", "None", ",", ...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Logger.WriteLine
log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path.
uiautomation/uiautomation.py
def WriteLine(log: Any, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. """ Logger.Write('{}\n'.format(log), consoleColor, writeToFile, printToStdout, logFile)
def WriteLine(log: Any, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. """ Logger.Write('{}\n'.format(log), consoleColor, writeToFile, printToStdout, logFile)
[ "log", ":", "any", "type", ".", "consoleColor", ":", "int", "a", "value", "in", "class", "ConsoleColor", "such", "as", "ConsoleColor", ".", "DarkGreen", ".", "writeToFile", ":", "bool", ".", "printToStdout", ":", "bool", ".", "logFile", ":", "str", "log", ...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2805-L2813
[ "def", "WriteLine", "(", "log", ":", "Any", ",", "consoleColor", ":", "int", "=", "-", "1", ",", "writeToFile", ":", "bool", "=", "True", ",", "printToStdout", ":", "bool", "=", "True", ",", "logFile", ":", "str", "=", "None", ")", "->", "None", ":...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Logger.ColorfullyWrite
log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyWrite('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames.
uiautomation/uiautomation.py
def ColorfullyWrite(log: str, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyWrite('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames. """ text = [] start = 0 while True: index1 = log.find('<Color=', start) if index1 >= 0: if index1 > start: text.append((log[start:index1], consoleColor)) index2 = log.find('>', index1) colorName = log[index1+7:index2] index3 = log.find('</Color>', index2 + 1) text.append((log[index2 + 1:index3], Logger.ColorNames[colorName])) start = index3 + 8 else: if start < len(log): text.append((log[start:], consoleColor)) break for t, c in text: Logger.Write(t, c, writeToFile, printToStdout, logFile)
def ColorfullyWrite(log: str, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyWrite('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames. """ text = [] start = 0 while True: index1 = log.find('<Color=', start) if index1 >= 0: if index1 > start: text.append((log[start:index1], consoleColor)) index2 = log.find('>', index1) colorName = log[index1+7:index2] index3 = log.find('</Color>', index2 + 1) text.append((log[index2 + 1:index3], Logger.ColorNames[colorName])) start = index3 + 8 else: if start < len(log): text.append((log[start:], consoleColor)) break for t, c in text: Logger.Write(t, c, writeToFile, printToStdout, logFile)
[ "log", ":", "str", ".", "consoleColor", ":", "int", "a", "value", "in", "class", "ConsoleColor", "such", "as", "ConsoleColor", ".", "DarkGreen", ".", "writeToFile", ":", "bool", ".", "printToStdout", ":", "bool", ".", "logFile", ":", "str", "log", "file", ...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2816-L2842
[ "def", "ColorfullyWrite", "(", "log", ":", "str", ",", "consoleColor", ":", "int", "=", "-", "1", ",", "writeToFile", ":", "bool", "=", "True", ",", "printToStdout", ":", "bool", "=", "True", ",", "logFile", ":", "str", "=", "None", ")", "->", "None"...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Logger.ColorfullyWriteLine
log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyWriteLine('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames.
uiautomation/uiautomation.py
def ColorfullyWriteLine(log: str, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyWriteLine('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames. """ Logger.ColorfullyWrite(log + '\n', consoleColor, writeToFile, printToStdout, logFile)
def ColorfullyWriteLine(log: str, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyWriteLine('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames. """ Logger.ColorfullyWrite(log + '\n', consoleColor, writeToFile, printToStdout, logFile)
[ "log", ":", "str", ".", "consoleColor", ":", "int", "a", "value", "in", "class", "ConsoleColor", "such", "as", "ConsoleColor", ".", "DarkGreen", ".", "writeToFile", ":", "bool", ".", "printToStdout", ":", "bool", ".", "logFile", ":", "str", "log", "file", ...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2845-L2855
[ "def", "ColorfullyWriteLine", "(", "log", ":", "str", ",", "consoleColor", ":", "int", "=", "-", "1", ",", "writeToFile", ":", "bool", "=", "True", ",", "printToStdout", ":", "bool", "=", "True", ",", "logFile", ":", "str", "=", "None", ")", "->", "N...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Logger.Log
log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path.
uiautomation/uiautomation.py
def Log(log: Any = '', consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. """ t = datetime.datetime.now() frame = sys._getframe(1) log = '{}-{:02}-{:02} {:02}:{:02}:{:02}.{:03} Function: {}, Line: {} -> {}\n'.format(t.year, t.month, t.day, t.hour, t.minute, t.second, t.microsecond // 1000, frame.f_code.co_name, frame.f_lineno, log) Logger.Write(log, consoleColor, writeToFile, printToStdout, logFile)
def Log(log: Any = '', consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. """ t = datetime.datetime.now() frame = sys._getframe(1) log = '{}-{:02}-{:02} {:02}:{:02}:{:02}.{:03} Function: {}, Line: {} -> {}\n'.format(t.year, t.month, t.day, t.hour, t.minute, t.second, t.microsecond // 1000, frame.f_code.co_name, frame.f_lineno, log) Logger.Write(log, consoleColor, writeToFile, printToStdout, logFile)
[ "log", ":", "any", "type", ".", "consoleColor", ":", "int", "a", "value", "in", "class", "ConsoleColor", "such", "as", "ConsoleColor", ".", "DarkGreen", ".", "writeToFile", ":", "bool", ".", "printToStdout", ":", "bool", ".", "logFile", ":", "str", "log", ...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2858-L2870
[ "def", "Log", "(", "log", ":", "Any", "=", "''", ",", "consoleColor", ":", "int", "=", "-", "1", ",", "writeToFile", ":", "bool", "=", "True", ",", "printToStdout", ":", "bool", "=", "True", ",", "logFile", ":", "str", "=", "None", ")", "->", "No...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Logger.DeleteLog
Delete log file.
uiautomation/uiautomation.py
def DeleteLog() -> None: """Delete log file.""" if os.path.exists(Logger.FileName): os.remove(Logger.FileName)
def DeleteLog() -> None: """Delete log file.""" if os.path.exists(Logger.FileName): os.remove(Logger.FileName)
[ "Delete", "log", "file", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2890-L2893
[ "def", "DeleteLog", "(", ")", "->", "None", ":", "if", "os", ".", "path", ".", "exists", "(", "Logger", ".", "FileName", ")", ":", "os", ".", "remove", "(", "Logger", ".", "FileName", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
Bitmap.FromHandle
Capture a native window to Bitmap by its handle. hwnd: int, the handle of a native window. left: int. top: int. right: int. bottom: int. left, top, right and bottom are control's internal postion(from 0,0). Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def FromHandle(self, hwnd: int, left: int = 0, top: int = 0, right: int = 0, bottom: int = 0) -> bool: """ Capture a native window to Bitmap by its handle. hwnd: int, the handle of a native window. left: int. top: int. right: int. bottom: int. left, top, right and bottom are control's internal postion(from 0,0). Return bool, True if succeed otherwise False. """ self.Release() root = GetRootControl() rect = ctypes.wintypes.RECT() ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect)) left, top, right, bottom = left + rect.left, top + rect.top, right + rect.left, bottom + rect.top self._bitmap = _DllClient.instance().dll.BitmapFromWindow(root.NativeWindowHandle, left, top, right, bottom) self._getsize() return self._bitmap > 0
def FromHandle(self, hwnd: int, left: int = 0, top: int = 0, right: int = 0, bottom: int = 0) -> bool: """ Capture a native window to Bitmap by its handle. hwnd: int, the handle of a native window. left: int. top: int. right: int. bottom: int. left, top, right and bottom are control's internal postion(from 0,0). Return bool, True if succeed otherwise False. """ self.Release() root = GetRootControl() rect = ctypes.wintypes.RECT() ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect)) left, top, right, bottom = left + rect.left, top + rect.top, right + rect.left, bottom + rect.top self._bitmap = _DllClient.instance().dll.BitmapFromWindow(root.NativeWindowHandle, left, top, right, bottom) self._getsize() return self._bitmap > 0
[ "Capture", "a", "native", "window", "to", "Bitmap", "by", "its", "handle", ".", "hwnd", ":", "int", "the", "handle", "of", "a", "native", "window", ".", "left", ":", "int", ".", "top", ":", "int", ".", "right", ":", "int", ".", "bottom", ":", "int"...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2941-L2959
[ "def", "FromHandle", "(", "self", ",", "hwnd", ":", "int", ",", "left", ":", "int", "=", "0", ",", "top", ":", "int", "=", "0", ",", "right", ":", "int", "=", "0", ",", "bottom", ":", "int", "=", "0", ")", "->", "bool", ":", "self", ".", "R...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Bitmap.FromControl
Capture a control to Bitmap. control: `Control` or its subclass. x: int. y: int. width: int. height: int. x, y: the point in control's internal position(from 0,0) width, height: image's width and height from x, y, use 0 for entire area, If width(or height) < 0, image size will be control's width(or height) - width(or height). Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def FromControl(self, control: 'Control', x: int = 0, y: int = 0, width: int = 0, height: int = 0) -> bool: """ Capture a control to Bitmap. control: `Control` or its subclass. x: int. y: int. width: int. height: int. x, y: the point in control's internal position(from 0,0) width, height: image's width and height from x, y, use 0 for entire area, If width(or height) < 0, image size will be control's width(or height) - width(or height). Return bool, True if succeed otherwise False. """ rect = control.BoundingRectangle while rect.width() == 0 or rect.height() == 0: #some controls maybe visible but their BoundingRectangle are all 0, capture its parent util valid control = control.GetParentControl() if not control: return False rect = control.BoundingRectangle if width <= 0: width = rect.width() + width if height <= 0: height = rect.height() + height handle = control.NativeWindowHandle if handle: left = x top = y right = left + width bottom = top + height else: while True: control = control.GetParentControl() handle = control.NativeWindowHandle if handle: pRect = control.BoundingRectangle left = rect.left - pRect.left + x top = rect.top - pRect.top + y right = left + width bottom = top + height break return self.FromHandle(handle, left, top, right, bottom)
def FromControl(self, control: 'Control', x: int = 0, y: int = 0, width: int = 0, height: int = 0) -> bool: """ Capture a control to Bitmap. control: `Control` or its subclass. x: int. y: int. width: int. height: int. x, y: the point in control's internal position(from 0,0) width, height: image's width and height from x, y, use 0 for entire area, If width(or height) < 0, image size will be control's width(or height) - width(or height). Return bool, True if succeed otherwise False. """ rect = control.BoundingRectangle while rect.width() == 0 or rect.height() == 0: #some controls maybe visible but their BoundingRectangle are all 0, capture its parent util valid control = control.GetParentControl() if not control: return False rect = control.BoundingRectangle if width <= 0: width = rect.width() + width if height <= 0: height = rect.height() + height handle = control.NativeWindowHandle if handle: left = x top = y right = left + width bottom = top + height else: while True: control = control.GetParentControl() handle = control.NativeWindowHandle if handle: pRect = control.BoundingRectangle left = rect.left - pRect.left + x top = rect.top - pRect.top + y right = left + width bottom = top + height break return self.FromHandle(handle, left, top, right, bottom)
[ "Capture", "a", "control", "to", "Bitmap", ".", "control", ":", "Control", "or", "its", "subclass", ".", "x", ":", "int", ".", "y", ":", "int", ".", "width", ":", "int", ".", "height", ":", "int", ".", "x", "y", ":", "the", "point", "in", "contro...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L2961-L3002
[ "def", "FromControl", "(", "self", ",", "control", ":", "'Control'", ",", "x", ":", "int", "=", "0", ",", "y", ":", "int", "=", "0", ",", "width", ":", "int", "=", "0", ",", "height", ":", "int", "=", "0", ")", "->", "bool", ":", "rect", "=",...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Bitmap.FromFile
Load image from a file. filePath: str. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def FromFile(self, filePath: str) -> bool: """ Load image from a file. filePath: str. Return bool, True if succeed otherwise False. """ self.Release() self._bitmap = _DllClient.instance().dll.BitmapFromFile(ctypes.c_wchar_p(filePath)) self._getsize() return self._bitmap > 0
def FromFile(self, filePath: str) -> bool: """ Load image from a file. filePath: str. Return bool, True if succeed otherwise False. """ self.Release() self._bitmap = _DllClient.instance().dll.BitmapFromFile(ctypes.c_wchar_p(filePath)) self._getsize() return self._bitmap > 0
[ "Load", "image", "from", "a", "file", ".", "filePath", ":", "str", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L3004-L3013
[ "def", "FromFile", "(", "self", ",", "filePath", ":", "str", ")", "->", "bool", ":", "self", ".", "Release", "(", ")", "self", ".", "_bitmap", "=", "_DllClient", ".", "instance", "(", ")", ".", "dll", ".", "BitmapFromFile", "(", "ctypes", ".", "c_wch...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Bitmap.ToFile
Save to a file. savePath: str, should end with .bmp, .jpg, .jpeg, .png, .gif, .tif, .tiff. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def ToFile(self, savePath: str) -> bool: """ Save to a file. savePath: str, should end with .bmp, .jpg, .jpeg, .png, .gif, .tif, .tiff. Return bool, True if succeed otherwise False. """ name, ext = os.path.splitext(savePath) extMap = {'.bmp': 'image/bmp' , '.jpg': 'image/jpeg' , '.jpeg': 'image/jpeg' , '.gif': 'image/gif' , '.tif': 'image/tiff' , '.tiff': 'image/tiff' , '.png': 'image/png' } gdiplusImageFormat = extMap.get(ext.lower(), 'image/png') return bool(_DllClient.instance().dll.BitmapToFile(self._bitmap, ctypes.c_wchar_p(savePath), ctypes.c_wchar_p(gdiplusImageFormat)))
def ToFile(self, savePath: str) -> bool: """ Save to a file. savePath: str, should end with .bmp, .jpg, .jpeg, .png, .gif, .tif, .tiff. Return bool, True if succeed otherwise False. """ name, ext = os.path.splitext(savePath) extMap = {'.bmp': 'image/bmp' , '.jpg': 'image/jpeg' , '.jpeg': 'image/jpeg' , '.gif': 'image/gif' , '.tif': 'image/tiff' , '.tiff': 'image/tiff' , '.png': 'image/png' } gdiplusImageFormat = extMap.get(ext.lower(), 'image/png') return bool(_DllClient.instance().dll.BitmapToFile(self._bitmap, ctypes.c_wchar_p(savePath), ctypes.c_wchar_p(gdiplusImageFormat)))
[ "Save", "to", "a", "file", ".", "savePath", ":", "str", "should", "end", "with", ".", "bmp", ".", "jpg", ".", "jpeg", ".", "png", ".", "gif", ".", "tif", ".", "tiff", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L3015-L3031
[ "def", "ToFile", "(", "self", ",", "savePath", ":", "str", ")", "->", "bool", ":", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "savePath", ")", "extMap", "=", "{", "'.bmp'", ":", "'image/bmp'", ",", "'.jpg'", ":", "'image/jpeg'"...
2cc91060982cc8b777152e698d677cc2989bf263
valid
Bitmap.GetPixelColor
Get color value of a pixel. x: int. y: int. Return int, argb color. b = argb & 0x0000FF g = (argb & 0x00FF00) >> 8 r = (argb & 0xFF0000) >> 16 a = (argb & 0xFF0000) >> 24
uiautomation/uiautomation.py
def GetPixelColor(self, x: int, y: int) -> int: """ Get color value of a pixel. x: int. y: int. Return int, argb color. b = argb & 0x0000FF g = (argb & 0x00FF00) >> 8 r = (argb & 0xFF0000) >> 16 a = (argb & 0xFF0000) >> 24 """ return _DllClient.instance().dll.BitmapGetPixel(self._bitmap, x, y)
def GetPixelColor(self, x: int, y: int) -> int: """ Get color value of a pixel. x: int. y: int. Return int, argb color. b = argb & 0x0000FF g = (argb & 0x00FF00) >> 8 r = (argb & 0xFF0000) >> 16 a = (argb & 0xFF0000) >> 24 """ return _DllClient.instance().dll.BitmapGetPixel(self._bitmap, x, y)
[ "Get", "color", "value", "of", "a", "pixel", ".", "x", ":", "int", ".", "y", ":", "int", ".", "Return", "int", "argb", "color", ".", "b", "=", "argb", "&", "0x0000FF", "g", "=", "(", "argb", "&", "0x00FF00", ")", ">>", "8", "r", "=", "(", "ar...
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L3033-L3044
[ "def", "GetPixelColor", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ")", "->", "int", ":", "return", "_DllClient", ".", "instance", "(", ")", ".", "dll", ".", "BitmapGetPixel", "(", "self", ".", "_bitmap", ",", "x", ",", "y", ")" ]
2cc91060982cc8b777152e698d677cc2989bf263
valid
Bitmap.SetPixelColor
Set color value of a pixel. x: int. y: int. argb: int, color value. Return bool, True if succeed otherwise False.
uiautomation/uiautomation.py
def SetPixelColor(self, x: int, y: int, argb: int) -> bool: """ Set color value of a pixel. x: int. y: int. argb: int, color value. Return bool, True if succeed otherwise False. """ return _DllClient.instance().dll.BitmapSetPixel(self._bitmap, x, y, argb)
def SetPixelColor(self, x: int, y: int, argb: int) -> bool: """ Set color value of a pixel. x: int. y: int. argb: int, color value. Return bool, True if succeed otherwise False. """ return _DllClient.instance().dll.BitmapSetPixel(self._bitmap, x, y, argb)
[ "Set", "color", "value", "of", "a", "pixel", ".", "x", ":", "int", ".", "y", ":", "int", ".", "argb", ":", "int", "color", "value", ".", "Return", "bool", "True", "if", "succeed", "otherwise", "False", "." ]
yinkaisheng/Python-UIAutomation-for-Windows
python
https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/2cc91060982cc8b777152e698d677cc2989bf263/uiautomation/uiautomation.py#L3046-L3054
[ "def", "SetPixelColor", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "argb", ":", "int", ")", "->", "bool", ":", "return", "_DllClient", ".", "instance", "(", ")", ".", "dll", ".", "BitmapSetPixel", "(", "self", ".", "_bitmap", ","...
2cc91060982cc8b777152e698d677cc2989bf263